我是一个相当新手在编程.I写了下面的代码,以便提示用户输入密码加密文件,但它只是工作时,密码的长度是8,我能做什么,以接受任何数量的字符的密码?
string pass = textBox2.Text.ToString();
string password = @"" + pass + "";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(@"c:\\users\\new", FileMode.Create);
name = fsCrypt.Name;
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(filename, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);发布于 2010-06-10 18:13:07
只有当GetBytes()的结果是合法的KeySize时,使用Encoding.GetBytes()直接从您的密码派生密钥才有效。
更重要的是,它是一个非常弱的密钥,特别是当您选择Unicode编码时。"foobar“键中的字节模式是66 00 6F 00 6F 00 62 00 61 00 72 00。你看到所有的00字节了吗?
官方的方法是使用Rfc2898DeriveBytes类。此外,使用密钥作为IV可能也不是一个好主意,我对此不是完全确定。
另请参阅this SO question。
发布于 2010-06-10 18:04:20
您需要一个函数,该函数将从您的密码中获取Rijndael的有效密钥长度,目前,您使用UnicodeEncoding.GetBytes只会为某些离散长度的密码提供密钥长度,正如您已经发现的那样。
您应该使用另一个函数来从您的密码中获取密钥-也许可以获取您已经生成的字节数组,并在其上运行一个加密散列函数,如SHA1。SHA1将为您提供128位长度,就像您当前使用的8字符密码一样,但与密码的长度无关。
发布于 2010-06-10 18:29:31
查看PasswordDeriveBytes
http://msdn.microsoft.com/en-us/library/system.security.cryptography.passwordderivebytes(v=VS.100).aspx
你需要一个固定的Salt值以及传递的值,这会阻止人们从算法中计算出密码。
它在TripleDES中的用法是这样的,在Rijndael中应该很容易修改:
// Create a TripleDESCryptoServiceProvider object.
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
// Create a PasswordDeriveBytes object and then create
// a TripleDES key from the password and salt.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);
// Create the key and set it to the Key property
// of the TripleDESCryptoServiceProvider object.
tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);https://stackoverflow.com/questions/3013368
复制相似问题