/// <summary> /// Encode the data. The data is encrypted using the default encryption algorithm (AES-256), /// then the AES key is encrypted using RSA and the RSA public key is appended. /// </summary> /// <param name="value">The data to encode</param> /// <exception cref="ArgumentNullException">The argument 'value' is null.</exception> /// <exception cref="ArgumentException">The argument 'value' contains zero bytes.</exception> /// <exception cref="InvalidOperationException">The EncryptionKey is null.</exception> /// <returns>Encoded data</returns> public override byte[] Encode(byte[] value) { if (null == value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (0 == value.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID6044)); } RSA encryptionKey = EncryptionKey; if (null == encryptionKey) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6043)); } byte[] rsaHash; byte[] encryptedKeyAndIV; byte[] encryptedData; using (HashAlgorithm hash = CryptoHelper.CreateHashAlgorithm(_hashName)) { rsaHash = hash.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey.ToXmlString(false))); } using (SymmetricAlgorithm encryptionAlgorithm = CryptoHelper.NewDefaultEncryption()) { encryptionAlgorithm.GenerateIV(); encryptionAlgorithm.GenerateKey(); using (ICryptoTransform encryptor = encryptionAlgorithm.CreateEncryptor()) { encryptedData = encryptor.TransformFinalBlock(value, 0, value.Length); } RSACryptoServiceProvider provider = encryptionKey as RSACryptoServiceProvider; if (provider == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6041)); } // // Concatenate the Key and IV in an attempt to avoid two minimum block lengths in the cookie // byte[] keyAndIV = new byte[encryptionAlgorithm.Key.Length + encryptionAlgorithm.IV.Length]; Array.Copy(encryptionAlgorithm.Key, keyAndIV, encryptionAlgorithm.Key.Length); Array.Copy(encryptionAlgorithm.IV, 0, keyAndIV, encryptionAlgorithm.Key.Length, encryptionAlgorithm.IV.Length); encryptedKeyAndIV = CngLightup.OaepSha1Encrypt(encryptionKey, keyAndIV); } using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(rsaHash); bw.Write(encryptedKeyAndIV.Length); bw.Write(encryptedKeyAndIV); bw.Write(encryptedData.Length); bw.Write(encryptedData); bw.Flush(); } return(ms.ToArray()); } }