如何在使用 crypto c# 4.0 时生成相同的密钥
嗨,我正在尝试加密和解密字符串值...我通过使用手动密钥来实现它,例如...
private static byte[] _salt = Encoding.ASCII.GetBytes("123456789abcdefg");
并且我创建了密钥和 iv 之类的
Rfc2898DeriveBytes rfcDeriveBytes = new Rfc2898DeriveBytes(password, _salt);
rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Key = rfcDeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
rijndaelManaged.IV = rfcDeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);
,但我想动态生成相同的密钥...我的意思是如何动态生成 _salt 。 ..
hi im trying to encrypt and decrypt string value... i made it by using manual key like...
private static byte[] _salt = Encoding.ASCII.GetBytes("123456789abcdefg");
and i created key and iv like
Rfc2898DeriveBytes rfcDeriveBytes = new Rfc2898DeriveBytes(password, _salt);
rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Key = rfcDeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
rijndaelManaged.IV = rfcDeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);
but i wanna generate the same key dynamically... i mean how can i generate _salt dynamically...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rfc2898DeriveBytes
类可以为您生成随机盐 - 只需 将所需的盐大小传递给适当的构造函数。并且不要忘记将生成的盐存储在安全的地方 - 它无法确定性地重新生成,并且没有它,您将无法重新创建密钥和 IV 进行解密。然后解密:
The
Rfc2898DeriveBytes
class can generate a random salt for you - just pass the required salt size to the appropriate constructor. And don't forget to store the generated salt somewhere safe - it can't be deterministically regenerated, and without it you won't be able to recreate your key and IV for decryption.And then to decrypt:
“盐”不是秘密的,您可以将其包含在加密数据中。加密/解密时不能使用不同的盐,并且为了有效,您应该对每条消息使用不同的盐。
您可以使用 System.Security.Cryptography.RandomNumberGenerator 类来创建 Salt。
The 'salt' is not secret, you can include it with the encrypted data. You cannot use different salts while encrypting/decrypting, and to be effective you should use a different salt for each message.
You can use the
System.Security.Cryptography.RandomNumberGenerator
class to create a Salt.