2013-03-29 74 views
1

我有一些使用RFC2898DeriveBytes的問題。情況如下:我使用RSACryptoProvider創建公鑰/私鑰對,並使用Rfc2898來加密私鑰文件。我使用下面的代碼進行加密:RFC2898DeriveBytes不解密

Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(frm2.txtPassphrase.Text, saltbyte); 

// Encrypt the data. 
TripleDES encAlg = TripleDES.Create(); 
encAlg.Key = key.GetBytes(16); 

// Create the streams used for encryption. 
byte[] encrypted; 
using (FileStream fsEncrypt = new FileStream(@"D:\test.xml", FileMode.Create, System.IO.FileAccess.Write)) 
{ 
    using (CryptoStream csEncrypt = new CryptoStream(fsEncrypt, encAlg.CreateEncryptor(), CryptoStreamMode.Write)) 
    { 
      using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
      { 
       //Write all data to the stream. 
       swEncrypt.Write(privateKeyXml); 
      } 
     } 
} 

這是解密:

TripleDES decAlg = TripleDES.Create(); 
Rfc2898DeriveBytes key1 = new Rfc2898DeriveBytes(frm1.txtPassphrase.Text, saltbyte); 
decAlg.Key = key1.GetBytes(16); 

// Create the streams used for decryption. 
using (FileStream fsDecrypt = new FileStream(@"D:\test.xml", FileMode.Open, System.IO.FileAccess.Read)) 
{ 
    using (CryptoStream csDecrypt = new CryptoStream(fsDecrypt, decAlg.CreateDecryptor(), CryptoStreamMode.Read)) 
    { 
     using (StreamReader srDecrypt = new StreamReader(csDecrypt)) 
     { 

      // Read the decrypted bytes from the decrypting stream 
      // and place them in a string. 
      decPrivateKeyXml = srDecrypt.ReadToEnd(); 
     } 
    } 
} 

現在的問題是,當我拿到decPrivateKeyXml,所有除前幾個字出來正確的。第幾個字剛炒:

"�� ���dalue><Modulus>u9N+amIgXTw1zzJ+bxXoKaaGwCVFeXkKvdx0vhd24X7vvcJpnkA6gFgOeypbTTGm3if1QM/lyLN3qoprBkHJKDo7ldzj5a4L2Xb1tP1yUyNDban/KzkzsGK0h3fLO8UxRE6cHIB5cyEUmgmkjpFoXzz7DovUrZh3Z3qV20AHZLs=</Modulus><Exponent>AQAB</Exponent><P>5pCr4yPtn8ZyZskIpFM9pgZI1BUBIJYYhnYPywrMTj1smsQGuCswXNrcKsGvF6c9KrrXFF69AgbzcAsQwI449Q==</P><Q>0IvXoP8uELT/v8lG5R0YmvrgTfVQNJp8n8PT7J1dN3dsCDUHa+rK2Q4XSehFHT8XQgiENICkYg6xsdJqXXxY7w==</Q><DP>KwpSrAIm966J6JoanOJVHcsKiVyqazTZuzAK3rJTVT+uKG3zeynEy3CnrOufDeFQT8u1Hr5YtioqA35tUCS8iQ==</DP><DQ>UXZOxJTpaZ1KSaBWESlMcz2MYOdybRnrlHzqS4Ms5n2/tXUBcSZGFoNqlXQli0cZzrGE8v1NOQCEaPHImrv4AQ==</DQ><InverseQ>rX3TlQMreZvjm+fNS5UK90tj/KQQAlP0u5xxgEAUVfr8ZE/hsSOcB0MuXPyeGExRyRiBdSUsj64BHOVPH9+mcw==</InverseQ><D>H04JtNtz/3YolccZsZQaJM7/iIjtwmg9NRXIU2J/yueoN51ukxSra3bBux99JimPYVmRk+LSrpfS6xa07c8LIqMaC6nFQCVF6yJH3sHuDuL7Hob2dVZ+egyjeCVu8vyn1R4/SAZ4AaWtmc8c0Zt3hSvdDMCtN61HWegFmugvRkk=</D></RSAKeyValue>" 

我不知道什麼是錯的代碼....

回答

3

.NET使用了CBC加密隨機IV。你需要將這個IV與密文一起存儲,並用它初始化你的解密器。通常情況下,IV是以密文爲前綴的。

+0

謝謝謝謝! – coffeeak

相關問題