2013-01-11 47 views
1

当我调用以下方法从Windows应用程序解密字符串时,发现“填充无效且无法移除”错误。字符串是从一个asp.net应用程序加密的。两个应用程序引用相同的程序集我能够从asp.net应用程序加密和解密出任何问题。这里是我进行加密和解密的主要代码。填充无效,无法使用Rijndael解密进行删除

private static byte[] EncryptHelper(byte[] arrData, string Password, bool Encrypt) 
    { 
     //Create the SymetricAlgorithem object 
     SymmetricAlgorithm myAlg = new RijndaelManaged(); 

     //define a salt value to derive the key. 
     byte[] salt = System.Text.Encoding.ASCII.GetBytes("hjkhj877ffasah"); 

     //Instantiate Rfc2898DeriveBytes with the password and salt. 
     Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(Password, salt); 


     myAlg.Key = key.GetBytes(myAlg.KeySize/8); 
     myAlg.IV = key.GetBytes(myAlg.BlockSize/8); 
     myAlg.Padding = PaddingMode.PKCS7; 
     //Create the ICryptoTransform Object 
     ICryptoTransform encrytptor = Encrypt ? myAlg.CreateEncryptor() : myAlg.CreateDecryptor(); 

     //Create Memorystream to write the encrypted data 
     using (MemoryStream aStream = new MemoryStream()) 
     { 

      //Create the CryptoStream Ojbect using the aStream object 
      using (CryptoStream encryptStream = new CryptoStream(aStream, encrytptor, CryptoStreamMode.Write)) 
      { 
       //Write the contents to crypto stream 
       encryptStream.Write(arrData, 0, arrData.Length); 

       //Flush the cryptostream 
       encryptStream.FlushFinalBlock(); 

       //Reposition the memorystream to write the contents to an array. 
       aStream.Position = 0; 

      } 
      aStream.Flush(); 
      //Convert to an array and return 
      return aStream.ToArray(); 

     } 
    } 

这是我使用的纯文本转换自/至字节数组

private static byte[] GetBytes(string str) 
    { 
     byte[] bytes = new byte[str.Length * sizeof(char)]; 
     System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); 
     return bytes; 
    } 

    private static string GetString(byte[] bytes) 
    { 
     char[] chars = new char[bytes.Length/sizeof(char)]; 
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); 
     return new string(chars); 
    } 

对于持续密文到数据库我使用Convert.ToBase64String()和Convert.FromBase64String的方法。问题与我使用Rfc2898DeriveBytes类的方式有关吗?

+0

如果您有两个代码库,则显然需要包含这两个代码库。在这里阅读一些答案。关闭,没有足够的信息,否则“过于本地化”。 –

回答

2

嗯,我想提一提,从安全角度来看,你将不得不用相同的密码每个消息相同IV是非常重要的,并且可预测的IV是一个非常大的不无

之后,我有点不想再看它,看看有什么问题,在stackoverflow上有很多非常不好的剪切和粘贴C#加密,他们只是坐在那里没有更新的机制,没有人再看着他们,除了人们发现他们再次切割和粘贴。

Modern Examples of Symmetric Authenticated Encryption of a string. c#

我尽量保持它的最新状态和审查。

相关问题