private AesEncryptionResult PerformEncryption( string toEncrypt, JweAlg alg, JweProtectedHeader protectedHeader, JsonWebKey jsonWebKey, Func <byte[][], byte[]> callback) { // Get the content encryption key var contentEncryptionKey = _aesEncryptionHelper.GenerateContentEncryptionKey(_keySize); // Encrypt the content encryption key var encryptedContentEncryptionKey = _aesEncryptionHelper.EncryptContentEncryptionKey( contentEncryptionKey, alg, jsonWebKey); var contentEncryptionKeySplitted = GetKeysFromContentEncryptionKey(contentEncryptionKey); var hmacKey = callback(contentEncryptionKeySplitted); var aesCbcKey = contentEncryptionKeySplitted[1]; var iv = ByteManipulator.GenerateRandomBytes(_keySize / 2); // Encrypt the plain text & create cipher text. var cipherText = _aesEncryptionHelper.EncryptWithAesAlgorithm( toEncrypt, aesCbcKey, iv); // Calculate the additional authenticated data. var serializedProtectedHeader = protectedHeader.SerializeWithDataContract(); var aad = Encoding.UTF8.GetBytes(serializedProtectedHeader); // Calculate the authentication tag. var al = ByteManipulator.LongToBytes(aad.Length * 8); var hmacInput = ByteManipulator.Concat(aad, iv, cipherText, al); var hmacValue = ComputeHmac(_keySize, hmacKey, hmacInput); var authenticationTag = ByteManipulator.SplitByteArrayInHalf(hmacValue)[0]; return(new AesEncryptionResult { Iv = iv, CipherText = cipherText, EncryptedContentEncryptionKey = encryptedContentEncryptionKey, AuthenticationTag = authenticationTag }); }
public byte[] GenerateContentEncryptionKey(int keySize) { return(ByteManipulator.GenerateRandomBytes(keySize)); }