使用C#进行AES解密

时间:2014-12-09 08:47:58

标签: c# c++ encryption aes

我在C ++中使用Crypto ++来加密字符串。现在我想用C#解密这个密文,但它不起作用。

加密字符串的我的C ++代码如下:

string encrypt(string data)
{
  // Key and IV setup
  std::string key = "0123456789abcdef";
  std::string iv = "aaaaaaaaaaaaaaaa";

  std::string plaintext = data;
  std::string ciphertext;

  // Create Cipher Text
  CryptoPP::AES::Encryption aesEncryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
  CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, (byte *)iv.c_str());

  CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext));
  stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length() + 1);
  stfEncryptor.MessageEnd();

  return ciphertext;
}

要在C ++中解密代码,我可以使用此代码

CryptoPP::AES::Decryption aesDecryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, (byte *)iv.c_str() );

CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( result_string.c_str() ), result_string.size() );
stfDecryptor.MessageEnd()

但我需要在C#应用程序中解密代码,因此我使用这种方法:

static string Decrypt(byte[] cipherText)
{
  if (cipherText == null || cipherText.Length <= 0)
    throw new ArgumentNullException("cipherText");

  byte[] Key = GetBytes(ConfigurationManager.AppSettings["aes_key"]);
  byte[] IV = GetBytes(ConfigurationManager.AppSettings["aes_iv"]);

  // Declare the string used to hold the decrypted text.
  string plaintext = null;

  // Create an RijndaelManaged object with the specified key and IV.
  using (RijndaelManaged rijAlg = new RijndaelManaged())
  {
    rijAlg.Key = Key;
    rijAlg.IV = IV;

    // Create a decrytor to perform the stream transform.
    ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

    // Create the streams used for decryption.
    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
    {
      using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
      {
        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
        {
          // Read the decrypted bytes from the decrypting stream
          // and place them in a string.
          plaintext = srDecrypt.ReadToEnd();
        }
      }
    }
  }

  return plaintext;
}

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;
}

如果我尝试解密密文,我收到消息,指出的初始化向量与此算法的块大小不匹配。

我不知道为什么这不起作用,我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

尝试像这样设置你的IV:

rijAlg.IV = new byte[]{ 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97 }; 

确保IV具有正好128位(以及所有a&#39; s,如c ++示例中所示)。

如果此方法有效,请确保从配置中正确读取IV。 ConfigurationManager.AppSettings["aes_iv"]的值可能为空,或者长度不为16.