在F#中实现AES加密(根据MSDN C#示例)

时间:2013-09-05 12:01:45

标签: .net encryption f# cryptography aes

可能我有一个愚蠢的问题,但我无法让它发挥作用。 我根据C#中的MSDN示例在F#中进行AES加密\解密:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.aes.aspx

我的加密方法如下:

let EncryptStringToBytesAes (plainText : string) (key : byte[]) (iv : byte[]) =
    use aesAlg = Aes.Create()
    aesAlg.Key <- key
    aesAlg.IV <- iv
    // Create a decrytor to perform the stream transform.
    let encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
    // Create the streams used for encryption. 
    use msEncrypt = new MemoryStream()
    use csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
    use swEncrypt = new StreamWriter(csEncrypt)
    swEncrypt.Write(plainText)
    msEncrypt.ToArray()

问题是这个方法总是返回一个空的字节数组。我没有任何例外。密钥和IV是适当的字节数组。好像StreamWriter不起作用......

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

以@ usr的回答为基础......

确保流关闭的最简单方法是在调用use之前将ToArray语句放在超出范围的块中。

let EncryptStringToBytesAes (plainText : string) (key : byte[]) (iv : byte[]) =
    use aesAlg = Aes.Create()
    aesAlg.Key <- key
    aesAlg.IV <- iv
    // Create a decrytor to perform the stream transform.
    let encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
    // Create the streams used for encryption. 
    use msEncrypt = new MemoryStream()
    (
      use csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
      use swEncrypt = new StreamWriter(csEncrypt)
      swEncrypt.Write(plainText)
    )
    msEncrypt.ToArray()

答案 1 :(得分:2)

在致电msEncrypt.ToArray之前,您必须清除所有中间流,或关闭它们,因为它们正在缓冲数据。

答案 2 :(得分:-2)

为了使其正常工作,我们需要显式关闭StreamWriter和CryptoStream