【发布时间】:2017-01-08 19:42:15
【问题描述】:
我很感兴趣,为什么加密/解密仅适用于磁盘文件上的小 0 字节大小,但停止使用较大的文件,我收到错误 The input data is not a complete block 和 Index 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();
}
}
}
}
【问题讨论】:
标签: c# encryption cryptography aes