AES加密仅适用于磁盘上小的0字节大小的文件

时间:2017-01-08 19:42:15

标签: c# encryption cryptography aes

我感兴趣的是,为什么加密/解密只能在磁盘文件上使用小的0字节大小,但是停止使用较大的文件,我会收到错误The input data is not a complete blockIndex was outside the bounds of the array

我使用ECDiffieHellmanCng在两侧生成相同的对称密钥。

加密端密钥交换:

using (ECDiffieHellmanCng sendingMode = new ECDiffieHellmanCng())
{
     sendingMode.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
     sendingMode.HashAlgorithm = CngAlgorithm.Sha256;
     sendersPublicKey = sendingMode.PublicKey.ToByteArray(); 
     CngKey secretKey = CngKey.Import(receiversPublicKey, CngKeyBlobFormat.EccPublicBlob);
     sendersKey = sendingMode.DeriveKeyMaterial(CngKey.Import(receiversPublicKey, CngKeyBlobFormat.EccPublicBlob)); 
     byte[] encryptedFile = null;
     byte[] ivFile = null;
     byte[] fileBytes = File.ReadAllBytes(fileToSendPath);
     Encryption(sendersKey, fileBytes, out encryptedFile, out ivFile);
}

接收方交流:

using (ECDiffieHellmanCng receivingMode = new ECDiffieHellmanCng())
{
     receivingMode.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
     receivingMode.HashAlgorithm = CngAlgorithm.Sha256;
     receiversPublicKey = receivingMode.PublicKey.ToByteArray();

     CngKey secretKey = CngKey.Import(sendersPublicKey, CngKeyBlobFormat.EccPublicBlob);
     receiversKey = receivingMode.DeriveKeyMaterial(CngKey.Import(sendersPublicKey, CngKeyBlobFormat.EccPublicBlob));
     byte[] decryptedFile = new byte[50000000];
     Decryption(encryptedFile, ivFile, out decryptedFile); 
}

加密/解密方法:

private void Encryption(byte[] key, byte[] unencryptedMessage,out byte[] encryptedMessage, out byte[] iv)
{
     using (Aes aes = new AesCryptoServiceProvider())
     {
           aes.Key = key;
           iv = aes.IV;

           // Encrypt the message
           using (MemoryStream ciphertext = new MemoryStream())
           using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
           {
               cs.Write(unencryptedMessage, 0, unencryptedMessage.Length);
               cs.Close();
               encryptedMessage = ciphertext.ToArray();
           }
      }
}

private void Decryption(byte[] encryptedMessage, byte[] iv, out byte[] decryptedMessage)
{
      using (Aes aes = new AesCryptoServiceProvider())
      {
           aes.Key = receiversKey;
           aes.IV = iv;
           // Decrypt the message
           using (MemoryStream decryptedBytes = new MemoryStream())
           {
                using (CryptoStream cs = new CryptoStream(decryptedBytes, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(encryptedMessage, 0, encryptedMessage.Length);
                    cs.Close();
                    decryptedMessage = decryptedBytes.ToArray();
                }
            }
       }
}

1 个答案:

答案 0 :(得分:1)

AES是一种分组密码,要求输入为块大小倍数,AES为16字节。简单的解决方案是使用PKCS#7(néePKCS#5)填充选项,填充将在加密时透明地添加,并在解密时删除。