代码之家  ›  专栏  ›  技术社区  ›  Mohammad

使用Rijndael加密

c#
  •  6
  • Mohammad  · 技术社区  · 14 年前

    我是一个编程新手。我写下面的代码是为了提示用户密码来加密文件,但它只在密码长度为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);
    
    3 回复  |  直到 11 年前
        1
  •  1
  •   Community Tales Farias    7 年前

    直接从密码中派生密钥 Encoding.GetBytes() 只有当getBytes()的结果是合法的keysize时才有效。

    更重要的是,它是一个非常弱的密钥,特别是当您选择Unicode编码时。“foobar”键中的字节模式是 66 00 6F 00 6F 00 62 00 61 00 72 00 . 你看到所有的00字节了吗?

    官方的方法是使用 Rfc2898DeriveBytes 班级。另外,使用IV键可能不是一个好主意,我不完全确定这一点。

    也看到 this SO question .

        2
  •  2
  •   David M    14 年前

    您需要一个函数,该函数将从您的密码中获得Rijndael的有效密钥长度,现在,您可以使用 UnicodeEncoding.GetBytes 正如您所发现的,只会在某些离散的密码长度上给出这个值。

    您应该使用另一个函数从您的密码中获取一个密钥——可能使用您生成的字节数组,并在上面运行一个类似sha1的加密散列函数。sha1会给你一个128位的长度,就像你目前使用的8个字符的密码一样,但是不管密码的长度如何。

        3
  •  0
  •   badbod99    14 年前

    退房 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);