private static CryptographicKey DeriveKey(CryptographicKey keyDerivationKey)
        {
            using (HMACSHA512 hmac = CryptoAlgorithms.CreateHMACSHA512(keyDerivationKey.GetKeyMaterial()))
            {
                byte[] label, context;
                GetKeyDerivationParameters(out label, out context);

                byte[] derivedKey = DeriveKeyImpl(hmac, label, context, keyDerivationKey.KeyLength);
                return(new CryptographicKey(derivedKey));
            }
        }
Пример #2
0
        /// <summary>
        /// Returns an IV that's based solely on the contents of a buffer; useful for generating
        /// predictable IVs for ciphertexts that need to be cached. The output value is only
        /// appropriate for use as an IV and must not be used for any other purpose.
        /// </summary>
        /// <remarks>This method uses an iterated unkeyed SHA256 to calculate the IV.</remarks>
        /// <param name="buffer">The input buffer over which to calculate the IV.</param>
        /// <param name="ivBitLength">The requested length (in bits) of the IV to generate.</param>
        /// <returns>The calculated IV.</returns>
        public static byte[] CreatePredictableIV(byte[] buffer, int ivBitLength)
        {
            byte[] output         = new byte[ivBitLength / 8];
            int    bytesCopied    = 0;
            int    bytesRemaining = output.Length;

            using (SHA256 sha256 = CryptoAlgorithms.CreateSHA256())
            {
                while (bytesRemaining > 0)
                {
                    byte[] hashed = sha256.ComputeHash(buffer);

                    int bytesToCopy = Math.Min(bytesRemaining, hashed.Length);
                    Buffer.BlockCopy(hashed, 0, output, bytesCopied, bytesToCopy);

                    bytesCopied    += bytesToCopy;
                    bytesRemaining -= bytesToCopy;

                    buffer = hashed; // next iteration (if it occurs) will operate over the block just hashed
                }
            }

            return(output);
        }