也许我有一个愚蠢的问题,但我无法使其工作。在F#中实现AES加密(根据MSDN C#示例)
http://msdn.microsoft.com/en-us/library/system.security.cryptography.aes.aspx
我的加密方法如下:: 我在F#根据MSDN例子是在C#做AES加密\解密
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不工作...
谢谢你的帮助。
您也可以使用'encryptor.TransformFinalBlock'的简化。使用'CryptoStream'进行短消息不必要的复杂化。 – CodesInChaos
作为旁注:1)需要为每条消息随机生成一个IV。跨消息重用IV是不安全的。 2)不要忘记在encrypt-then-mac方案中添加一个合适的MAC。其他主动攻击如填充魔咒可能会轻易破坏您的加密。 – CodesInChaos