在C#中生成一个128位字符串 [英] Generate a 128-bit string in C#
问题描述
我正在用C#开发一个可加密用户和管理员密码的类项目.为了加密,我使用了 TripleDESCryptoServiceProvider
.
I am developing a class project in C# that encrypts the users and admins passwords. To encrypt I'm using the TripleDESCryptoServiceProvider
.
在配置应用程序中,用户输入用于加密和解密密码的密钥.我想要一个按钮来生成用于帮助用户的密钥,但是我对如何随机生成128位不知所措.如何生成具有128位的密钥?
In the configuration app the user enters the key to be used for encryption and decryption of the passwords. I want to have a button to generate a key to help the user but I'm at a loss as to how I generate the 128 bits randomly. How a generate a key with 128-bits?
推荐答案
To generate a random value for crypto use, you should use RNGCryptoServiceProvider
:
byte[] bytes = new byte[16];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(bytes);
要将此字节序列转换为字符串,可以使用十六进制( BitConverter.ToString
)或Base64( Convert.ToBase64String
).
To turn this sequence of bytes into a string you could use hex (BitConverter.ToString
) or Base64 (Convert.ToBase64String
).
但是这里有一些奇怪的地方:
But there are some strange points here:
- 3DES使用168位密钥
- 如果要使用对称加密,则可能应该使用AES.3DES并不是完全坏掉的,但是它仅用于传统用途.
- 请注意您选择的分组密码操作模式.您通常需要适当的IV,MAC和安全链接模式
- 通常,您实际上通常应该对密码进行哈希处理,而不是对密码进行加密.请参阅如何安全地对密码进行哈希处理?有关安全性.了解详情.
- 3DES uses a 168 bit key
- If you want to use symmetric encryption, you should probably use AES. 3DES isn't totally broken, but it's pretty much for legacy use only.
- Be careful about the Block cipher mode of operation you're choosing. You typically need a proper IV, a MAC and a secure chaining mode
- Often you actually should hash passwords instead of encrypting them. See How to securely hash passwords? on security.SE for details.
这篇关于在C#中生成一个128位字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!