2015-08-15 56 views
2

一个文件,我发现这个代码在网站加密与Rijndael算法

private void EncryptFile(string inputFile) 
     { 

       string password = @"myKey123"; // Your Key Here 
       UnicodeEncoding UE = new UnicodeEncoding(); 
       byte[] key = UE.GetBytes(password); 

       string cryptFile = inputFile + ".enc"; 
       FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); 

       RijndaelManaged RMCrypto = new RijndaelManaged(); 

       CryptoStream cs = new CryptoStream(fsCrypt, 
        RMCrypto.CreateEncryptor(key, key), 
        CryptoStreamMode.Write); 

       FileStream fsIn = new FileStream(inputFile, FileMode.Open); 

       int data; 
       while ((data = fsIn.ReadByte()) != -1) 
        cs.WriteByte((byte)data); 


       fsIn.Close(); 
       cs.Close(); 
       fsCrypt.Close(); 

     } 

我有两个问题吧。第一个是password部分。我有一个生成随机字符串的函数:

public string CreatePassword(int length) 
     { 
      const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890*!=?&/"; 
      StringBuilder res = new StringBuilder(); 
      Random rnd = new Random(); 
      while (0 < length--){ 
       res.Append(valid[rnd.Next(valid.Length)]); 
      } 
      return res.ToString(); 
     } 

当我编辑这样的代码:

string password = CreatePassword(8); 

它的工作原理。但是当我增加密码大小(如10),我得到这个错误:

An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll 

有没有办法增加密码长度?或者我们可以认为它是安全的8长度?

其他问题:

我的输出文件inputFile + ".enc"当我删除".enc"第一部分我“这个文件是使用由另一个进程”错误。如何将加密的文件写入原始文件?

+0

您是否在调试模式下运行它,并提取有关该问题的更详细的异常? – Jens

+0

您不应该直接使用密码作为密钥,您应该使用['Rfc2898DeriveBytes'](https://msdn.microsoft.com/en-us/library/system)的基于密码的密钥派生函数“PBKDF”。 security.cryptography.rfc2898derivebytes(v = vs.110).aspx)类,其中包含PBKDF2。将密码字符串传入,然后使用它获取所需的字节数。 –

回答

1

RijndaelManaged有规则。下面的命令用于准备算法:

RMCrypto.CreateEncryptor(key, key) 

第一个参数是密钥,它必须是128,192或256位。第二个参数是IV。在给定的例子中,键和IV用作相同的。密码文本使用unicode转换为字节,因此它的长度为16字节= 128位。所以如果你使用不同的尺寸,那么你会得到错误。

您可以查看下面的文章好得多: Encrypting & Decrypting a String in C#