public byte[] Expand(HashAlgorithm hash, byte[] secret, byte[] seed, int length) { var hashLength = hash.HashSize / 8; var iterations = length / hashLength; if (length % hashLength > 0) { iterations++; } var hmac = new HMAC(hash, secret); var resMacs = new TlsStream(); var hmacs = new byte[iterations + 1][]; hmacs[0] = seed; for (var i = 1; i <= iterations; i++) { var hcseed = new TlsStream(); hmac.TransformFinalBlock(hmacs[i - 1], 0, hmacs[i - 1].Length); hmacs[i] = hmac.Hash; hcseed.Write(hmacs[i]); hcseed.Write(seed); hmac.TransformFinalBlock(hcseed.ToArray(), 0, (int)hcseed.Length); resMacs.Write(hmac.Hash); hcseed.Reset(); } var res = new byte[length]; Buffer.BlockCopy(resMacs.ToArray(), 0, res, 0, res.Length); resMacs.Reset(); return(res); }
private void createDecryptionCipher() { // Create and configure the symmetric algorithm switch (CipherAlgorithmType) { case CipherAlgorithmType.Des: decryptionAlgorithm = DES.Create(); break; case CipherAlgorithmType.Rc2: decryptionAlgorithm = RC2.Create(); break; case CipherAlgorithmType.Rc4: decryptionAlgorithm = new M.ARC4Managed(); break; case CipherAlgorithmType.TripleDes: decryptionAlgorithm = TripleDES.Create(); break; case CipherAlgorithmType.Rijndael: // only AES is really used - and we can use CommonCrypto for iOS and OSX this way decryptionAlgorithm = Aes.Create(); break; } // If it's a block cipher if (CipherMode == CipherMode.CBC) { // Configure encrypt algorithm decryptionAlgorithm.Mode = CipherMode; decryptionAlgorithm.Padding = PaddingMode.None; decryptionAlgorithm.KeySize = ExpandedKeyMaterialSize * 8; decryptionAlgorithm.BlockSize = blockSize * 8; } // Set the key and IV for the algorithm if (Context is ClientContext) { decryptionAlgorithm.Key = Context.ServerWriteKey; decryptionAlgorithm.IV = Context.ServerWriteIV; } else { decryptionAlgorithm.Key = Context.ClientWriteKey; decryptionAlgorithm.IV = Context.ClientWriteIV; } // Create decryption cipher DecryptionCipher = decryptionAlgorithm.CreateDecryptor(); // Create the HMAC if (Context is ClientContext) { ServerHMAC = new HMAC( CreateHashAlgorithm(), Context.Negotiating.ServerWriteMAC); } else { ClientHMAC = new HMAC( CreateHashAlgorithm(), Context.Negotiating.ClientWriteMAC); } }