在C#中生成一个128位字符串 [英] Generate a 128-bit string in C#

查看:80
本文介绍了在C#中生成一个128位字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆