c# - AES 填充并将密文写入磁盘文件

标签 c# c++ encryption padding crypto++

我有一个字符串,我使用 C++ 在 C++ 中使用以下方法加密它:

std::ifstream t(filename); //File to be encrypt
std::stringstream buffer;
buffer << t.rdbuf();

ofstream combined_file2(filename2); //Encrypted file
combined_file2 << encrypt(buffer.str());

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

  //Alternative
  //byte key[CryptoPP::AES::DEFAULT_KEYLENGTH], iv[CryptoPP::AES::BLOCKSIZE];
  //memset(key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
  //memset(iv, 0x00, CryptoPP::AES::BLOCKSIZE);

  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());

  //Alternative
  //CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
  //CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv);

  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# 应用程序中解密文件时,我收到一条消息,指出数据的长度无效。我认为字节数组的长度不是 16 的倍数,所以我得到了错误。我尝试使用填充,但它无法正常工作。

这是我解密文件的方法:

string plaintext = Decrypt(File.ReadAllBytes(path));

private 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;
     //for testing                
     rijAlg.IV = new byte[] { 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97 };

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

我该如何解决这个问题?是否有任何函数可以进行填充,或者填充的方式有误?

最佳答案

基于评论:

In C++ I save a file combined_file2 << encrypt(buffer.str()); which I read in my C# program string plaintext = Decrypt(File.ReadAllBytes(path));

我不认为嵌入的 NULL 会导致 encrypt 出现问题功能,因为它返回一个 string ,并且包括明确的长度。

但是,嵌入的 NULL 和文件在 C++ 中写入磁盘的方式(或在 C# 中从磁盘读取)将是一个问题,因为这将在第一个嵌入的 NULL 处停止:combined_file2 << encrypt(buffer.str()) .

也许像下面这样的东西会有所帮助:

StringSource ss(ciphertext, true /*pumpAll*/);
FileSink fs("my-encrypted-file.bin", true /*binary*/);
ss.TransferTo(fs);

如果您使用的是 C++ 流,则使用 write流对象上的方法:

ofstream combined_file2;
...
combined_file2.write(ciphertext.data(), ciphertext.size());

关于c# - AES 填充并将密文写入磁盘文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27385456/

相关文章:

c# - Blazor 服务器端是否有任何热重载?

c# - 在 MVC 4 中操作模型绑定(bind)

c# - Getter、setter 和属性最佳实践。 Java 与 C#

C++从指针遍历映射

encryption - 如何查询 CrystalReports CMS 数据库?

c# - webclient 远程服务器返回错误 : (500) Internal Server Error

c++ - 在子类中调用父函数

java - 我的 dba 知道他在做什么吗?

python - python中的RSA加密

c++ - 编译器在执行左值到右值转换时做了什么?