byte[] plainTextOctetsAsBytes = ByteUtil.convertUnsignedToSignedTwosComp(plainTextOctetsAsInts);
String encodedHeader = "eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJwMnMiOiIyV0NUY0paMVJ2ZF9DSn" +
"VKcmlwUTF3IiwicDJjIjo0MDk2LCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiY3R5Ijoi" +
"andrK2pzb24ifQ";
Base64Url base64url = new Base64Url();
Headers headers = new Headers();
headers.setFullHeaderAsJsonString(base64url.base64UrlDecodeToUtf8String(encodedHeader));
PbkdfKey pbkdfKey = new PbkdfKey(PASSWORD);
Pbes2HmacShaWithAesKeyWrapAlgorithm pbesAlg = new Pbes2HmacShaWithAesKeyWrapAlgorithm.HmacSha256Aes128();
Key derivedKey = pbesAlg.deriveForEncrypt(pbkdfKey, headers);
byte[] expectedDerived = ByteUtil.convertUnsignedToSignedTwosComp(new int[]{110, 171, 169, 92, 129, 92, 109, 117,
233, 242, 116, 233, 170, 14, 24, 75});
assertArrayEquals(expectedDerived, derivedKey.getEncoded());
// Generate a 256 bit random Content Encryption Key (CEK). In this example, the value is:
byte[] exampleCek = ByteUtil.convertUnsignedToSignedTwosComp(new int[]{111, 27, 25, 52, 66, 29, 20, 78, 92, 176, 56, 240, 65, 208, 82,
112, 161, 131, 36, 55, 202, 236, 185, 172, 129, 23, 153, 194, 195,
48, 253, 182});
WrappingKeyManagementAlgorithm keyWrap = new AesKeyWrapManagementAlgorithm.Aes128();
ContentEncryptionKeyDescriptor cekDesc = new ContentEncryptionKeyDescriptor(exampleCek.length, AesKey.ALGORITHM);
ContentEncryptionKeys contentEncryptionKeys = keyWrap.manageForEnc(derivedKey, cekDesc, exampleCek);
byte[] contentEncryptionKey = contentEncryptionKeys.getContentEncryptionKey();
assertArrayEquals(exampleCek, contentEncryptionKey);
byte[] expectedEncryptedKey = ByteUtil.convertUnsignedToSignedTwosComp(new int[]{78, 186, 151, 59, 11, 141, 81, 240, 213, 245, 83, 211, 53, 188,
134, 188, 66, 125, 36, 200, 222, 124, 5, 103, 249, 52, 117, 184, 140,
81, 246, 158, 161, 177, 20, 33, 245, 57, 59, 4});
byte[] encryptedKey = contentEncryptionKeys.getEncryptedKey();
String encodedEncryptedKey = base64url.base64UrlEncode(encryptedKey);
assertArrayEquals(expectedEncryptedKey, encryptedKey);
String encodedIv = "Ye9j1qs22DmRSAddIh-VnA";
byte[] iv = base64url.base64UrlDecode(encodedIv);
AesCbcHmacSha2ContentEncryptionAlgorithm aes128CbcHmacSha256 = new AesCbcHmacSha2ContentEncryptionAlgorithm.Aes128CbcHmacSha256();
byte[] aad = StringUtil.getBytesAscii(encodedHeader);
ContentEncryptionParts contentEncryptionParts = aes128CbcHmacSha256.encrypt(plainTextOctetsAsBytes, aad, contentEncryptionKey, iv);
byte[] authenticationTag = contentEncryptionParts.getAuthenticationTag();
String encodedTag = base64url.base64UrlEncode(authenticationTag);
byte[] ciphertext = contentEncryptionParts.getCiphertext();
String encodedCiphertext = base64url.base64UrlEncode(ciphertext);
String cs = CompactSerializer.serialize(encodedHeader, encodedEncryptedKey, encodedIv, encodedCiphertext, encodedTag);
assertThat(CS, is(equalTo(cs)));
}