Java Secure Cookie Library

Overview

Secure Cookie Library

Java library for security cookies, client-side pieces of data protected from reading and modifications by client with strong cryptography

  • Allows to store small pieces of data at client side protected from reading and modifications by client and by third party.
  • Uses strong encryption (AES with GCM) to encrypt, decipher and validate data.
  • Has no runtime dependencies, plain JDK is enough.

Short explanation of idea of secure cookie usage was presented at JPoint 2020 conference in "Cryptography for Java Developer" presentation that can be viewed (in Russian) here: https://youtu.be/YQEb1mjjpZg?t=1279

Build with Gradle CodeQL Maven Central

Installation

Gradle

dependencies {
  implementation group: 'io.github.vlsergey', name: 'seccookie', version: '1.0.0'
}

Maven

  <dependency>
    <groupId>io.github.vlsergeygroupId>
    <artifactId>seccookieartifactId>
    <version>1.0.0version>
  dependency>

Simple usage (SimpleSecCookieMapper)

// Define a way to obtain SecretKey. Usually it is part of application configuration.
// Note. It's better to store SecretKey instance in memory than recreating it from char[] or byte[] on each call.
SecretKey secretKey = /* ... */;
Supplier<SecretKey> secretKeySupplier = () -> secretKey;

// Define a way to (de)serialize your data type to/from byte array.
// It may be Java serialization, Jackson ObjectMapper call for complex objects, or simple getBytes() for Strings:
Function<String, byte[]> serializer = String::getBytes;
Function
   
    String>
    deserializer = String::new;

// Construct instance of SimpleSecCookieMapper
SimpleSecCookieMapper.Settings settings = new SimpleSecCookieMapper.Settings(
   serializer, deserializer, secretKeySupplier);
SimpleSecCookieMapper mapper = new SimpleSecCookieMapper(settings);

// use mapper to serialize to secure cookie

String dataToStoreInCookie = UUID.randomUUID().toString();
byte[] secCookie = mapper.writeValue( dataToStoreInCookie );

// sometimes one need to serialize it to String.
// We recommend `apache-codec` library for that:
String encoded = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(secCookie)

// Decoding and validation is quite straightforward
byte[] secCookie2 = org.apache.commons.codec.binary.Base64.decodeBase64( encoded )
try {
  return mapper.readValue(secCookie2);
} catch (WrongSecureCookieException exc) {
  // can be replaced with ControllerAdvice Exception handler
  throw RuntimeException("Supplied data is invalid", exc);
}

Key rolling technique

For long living and secure-oriented systems it may be required to provide a "key rolling" support where keys can be replaced in runtime without problems with existing user data. SimpleSecCookieMapper supports it via providing list of keys that can be used to try and decrypt secure cookie. All keys will be used in provided order and only after all of them tried single success result will be returned. I.e. there is no "fast first success" shortcut to prevent timing attacks (but at the cost of exception creation in JVM).

To provide multiple decryption key just set decryptionKeysSupplier property in SimpleSecCookieMapper.Settings:

SimpleSecCookieMapper.Settings settings = new SimpleSecCookieMapper.Settings(
   serializer, deserializer, secretKeySupplier);
settings.setDecryptionKeysSupplier = () -> Arrays.asList( secretKey1, secretKey2, secretKey3, ... );

There are 2 rules when changing keys configuration:

  • Encrypt with newest key.
  • Have all old keys in decryption keys list until keys/cookie TTL expired.

Assume we have configuration alike following:

encryptWith: secretKey2
decryptWith:
  - secretKey1
  - secretKey2

secretKey1 was used long time before. So we removing it from the list and add new secretKey3 to decryption keys list:

encryptWith: secretKey2
decryptWith:
  - secretKey2
  - secretKey3

After that (or at the same time -- it's safe to do it simultaneously) one need to replace encryption key with new one:

encryptWith: secretKey3
decryptWith:
  - secretKey2
  - secretKey3

Just make sure that encryption key is always somewhere in the list of decryption keys.

You might also like...

This is an android library to represent password strength.

This is an android library to represent password strength.

PasswordStrengthView This is an android library to represent password strength. Preview How to use? Add maven to your project gradle file allprojects

Jan 3, 2022

Library to easily configure API Key authentication in (parts of) your Spring Boot Application

42 API Key Authentication A library to easily configure API Key authentication in (parts of) your Spring Boot Application. Features Easily configure A

Dec 8, 2021

ByteSkriptQuery - A library for deploying ByteSkript as a backend web technology.

ByteSkriptQuery - A library for deploying ByteSkript as a backend web technology.

ByteSkriptQuery A language library for ByteSkript that allows it to be deployed as a backend web language. Not only does this allow the creation of ad

Jan 4, 2022

Java JWT: JSON Web Token for Java and Android

Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand library for creating and verifying JSON Web Tokens (JW

Dec 30, 2022

Java Project based on Java and Encryption using Cryptography algorithms

Symmetric-Encryption-Cryptography-in-Java Java Project based on Java and Encryption using Cryptography algorithms Project Aim Develop Java program to

Feb 3, 2022

A mitigation for CVE-2021-44228 (log4shell) that works by patching the vulnerability at runtime. (Works with any vulnerable java software, tested with java 6 and newer)

Log4jPatcher A Java Agent based mitigation for Log4j2 JNDI exploits. This agent employs 2 patches: Disabling all Lookup conversions (on supported Log4

Dec 16, 2022

Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...

Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...

pac4j is an easy and powerful security engine for Java to authenticate users, get their profiles and manage authorizations in order to secure web appl

Dec 30, 2022

Bouncy Castle Java Distribution (Mirror)

The Bouncy Castle Crypto Package For Java The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms, it was developed by t

Dec 30, 2022

PicketLink is a security framework for securing Java EE applications.

PicketLink http://picketlink.org Java EE Application Security Identity Management Federation Social REST Security Standard-based Security This reposit

Feb 21, 2022
Owner
Sergey Vladimirov
Sergey Vladimirov
Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Tink A multi-language, cross-platform library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse. Ubuntu

Google 12.9k Jan 3, 2023
KeepMyPassword for Desktop - keep your passwords locally and secure.

KeepMyPassword is an open-source project under MIT license. Its aim is to provide a REAL secure place to store all your sensitive data. Everything is stored locally on your device. No one apart from YOU will ever have access to your passwords. Code is available to see whenever you need it.

Adrian Goral 35 Dec 15, 2022
Java binding to the Networking and Cryptography (NaCl) library with the awesomeness of libsodium

kalium - Java binding to the Networking and Cryptography (NaCl) library A Java binding to Networking and Cryptography library by Daniel J. Bernstein.

Bruno Oliveira da Silva 206 Oct 5, 2022
A small and easy-to-use one-time password generator library for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP).

OTP-Java A small and easy-to-use one-time password generator for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP). Table of Contents Features Ins

Bastiaan Jansen 106 Dec 30, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Java

jCasbin News: still worry about how to write the correct jCasbin policy? Casbin online editor is coming to help! Try it at: http://casbin.org/editor/

Casbin 2k Dec 30, 2022
A library for bypassing all of Java's security mechanisms, visibility checks, and encapsulation measures via the JNI API

Narcissus: thwart strong encapsulation in JDK 16+ Narcissus is a JNI native code library that provides a small subset of the Java reflection API, whil

ToolFactory 29 Nov 3, 2022
A small and easy-to-use one-time password generator library for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP).

OTP-Java A small and easy-to-use one-time password generator for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP). Table of Contents Features Ins

Bastiaan Jansen 106 Dec 30, 2022
A Twitter-API library JAVA

Tweety A Twitter-API library for JAVA. Code for Authorization (Oauth 1) can be found here :Authorization This api conta

Rohit Kumar 2 Apr 26, 2022
Password4j is a user-friendly cryptographic library that supports Argon2, Bcrypt, Scrypt, PBKDF2 and various cryptographic hash functions.

Password4j is a Java user-friendly cryptographic library for hashing and checking passwords with different Key derivation functions (KDFs) and Cryptog

Password4J 246 Jan 5, 2023
The react-native Baidu voice library provides voice recognition, voice wake-up and voice synthesis interfaces. react-native百度语音库,提供语音识别,语音唤醒以及语音合成接口。

react-native-baidu-asr react-native-baidu-asr It is a Baidu speech library under React Native, which can perform speech recognition, speech wake-up an

dengweibin 11 Oct 12, 2022