/// <summary> /// MGF1 is a mask generation function, based on a /// hash function. MGF1 coincides with the mask generation functions /// defined in IEEE Std 1363-2000 and the draft ANSI X9.44. /// </summary> /// <param name="mgfSeed">Seed from which mask is generated, an octet string</param> /// <param name="maskLen">Intended length in octets of the mask, at most 2^32 hLen</param> /// <param name="hash"> /// Hash function (hLen denotes the length in octets of the hash /// function output) /// </param> /// <returns>An octet string of length maskLen</returns> /// <exception cref="MaskTooLongException"> /// Thrown when maskLen > 2^32*hLen /// </exception> public byte[] MGF1(byte[] mgfSeed, int maskLen, HashAlgorithm hash) { int hLen = hash.HashSize / 8; if (maskLen > BigInteger.Pow(2, 32) * hLen) { throw new MaskTooLongException("Mask too long"); } byte[] T = new byte[0]; for (BigInteger counter = 0; counter < (maskLen - 1) / hLen + 1; counter++) { byte[] C = dataPrimitives.I2OSP(counter, 4); byte[] H = hash.ComputeHash(ByteArraysUtils.Concat(mgfSeed, C)); T = ByteArraysUtils.Concat(T, H); } return(ByteArraysUtils.GetSubArray(T, 0, maskLen)); }
public byte[] Encrypt(byte[] data, string passphrase) { // Check arguments. if (data == null || data.Length <= 0) { throw new ArgumentNullException("plainText"); } if (passphrase == null || passphrase.Length <= 0) { throw new ArgumentNullException("Key"); } byte[] encrypted; byte[] IV; string plainText = Encoding.UTF8.GetString(data); // Create an Aes object // with the specified key and IV. using (Aes aesAlg = Aes.Create()) { aesAlg.Key = CreateKey(passphrase); // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); IV = aesAlg.IV; // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } // Write IV to the encrypted data header byte[] result = ByteArraysUtils.Concat(IV, encrypted); // Return the encrypted bytes from the memory stream. return(result); }