AesCng持久化密钥导出/导入:导入失败,出现CryptographicException:提供的句柄无效。 [英] AesCng persisted key export/import: Import fails with CryptographicException: The supplied handle is invalid.
问题描述
我可以创建持久的AES密钥
I can create the persisted AES key
public static bool CreateContainer(string name)
{
if (CngKey.Exists(name))
{
return false;
}
CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters()
{
ExportPolicy = CngExportPolicies.AllowPlaintextExport,
KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey
};
CngKey cngKey = CngKey.Create(new CngAlgorithm("AES"), name, keyCreationParameters);
cngKey.Dispose();
return true;
}
然后用它来加密/解密
public static byte[] Encrypt(string keyContainerName, byte[] clearText, byte[] iv)
{
AesCng aesCng = null;
ICryptoTransform crypto = null;
byte[] cipher = null;
try
{
aesCng = new AesCng(keyContainerName);
aesCng.IV = (iv == null ? new byte[aesCng.IV.Length] : iv);
crypto = aesCng.CreateEncryptor();
cipher = crypto.TransformFinalBlock(clearText, 0, clearText.Length);
}
finally
{
if (crypto != null)
{
crypto.Dispose();
}
if (aesCng != null)
{
aesCng.Clear();
aesCng.Dispose();
}
}
return cipher;
}
public static byte[] Decrypt(string keyContainerName, byte[] cipher, byte[] iv)
{
AesCng aesCng = null;
ICryptoTransform crypto = null;
byte[] clearText = null;
try
{
aesCng = new AesCng(keyContainerName);
aesCng.IV = (iv == null ? new byte[aesCng.IV.Length] : iv);
crypto = aesCng.CreateDecryptor();
clearText = crypto.TransformFinalBlock(cipher, 0, cipher.Length);
}
finally
{
if (crypto != null)
{
crypto.Dispose();
}
if (aesCng != null)
{
aesCng.Clear();
aesCng.Dispose();
}
}
return clearText;
}
我可以导出密钥
I am able to export the key
public static bool ExportKey(string name, out byte[] blob)
{
blob = null;
if (!CngKey.Exists(name))
{
return false;
}
CngKey cngKey = CngKey.Open(name);
blob = cngKey.Export(CngKeyBlobFormat.OpaqueTransportBlob);
cngKey.Dispose();
return true;
}
但是,当我尝试导入blob时,我收到一个CryptographicException:提供的句柄无效。
However, when I try to import the blob, I get a CryptographicException: The supplied handle is invalid.
public static void ImportKey(string name, byte[] blob)
{
CngKey cngKey = CngKey.Import(blob, CngKeyBlobFormat.OpaqueTransportBlob);
cngKey.Dispose();
}
我无法解释失败原因。
任何人都可以解决问题在这?谢谢。
Can anyone shed some light on this? Thanks.
推荐答案
您好L_E_R,
Hi L_E_R,
感谢您在此发帖。
为您服务问题,在加密操作期间发生错误时抛出CryptographicException。我猜你在AES和CNG会话之间使用了错误的格式。
For your question, CryptographicException is thrown when an error occurs during a cryptographic operation. I guess you use the wrong format between AES and CNG conversation.
这是一个关于CNG导入密钥的代码示例供你参考。
Here is a code sample about CNG to import key for your reference.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System;
namespace SecureTranferTest
{
class Program
{
/// <summary>
/// Anli's private key
/// </summary>
public static System.Security.Cryptography.CngKey anlikey = null;
//Anli's public key
public static byte[] anlipulicKey = null;
//bob's private key
public static System.Security.Cryptography.CngKey bobkey = null;
public static byte[] bobpulicKey = null;
static void Main(string[] args)
{
CreateKey();
AnliSendMessage("Nice day");//Anli send message to bob
AnliSendMessage("hello");//Anli send message to bob
Console.ReadKey();
}
public static void CreateKey()
{
anlikey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
anlipulicKey = anlikey.Export(CngKeyBlobFormat.EccPublicBlob);
bobkey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
bobpulicKey = bobkey.Export(CngKeyBlobFormat.EccPublicBlob);
}
public static void AnliSendMessage(string message)
{
byte[] rowData = Encoding.UTF8.GetBytes(message);
using (ECDiffieHellmanCng cng = new ECDiffieHellmanCng(anlikey))
{
using (CngKey bobkey = CngKey.Import(bobpulicKey, CngKeyBlobFormat.EccPublicBlob))
{
var sumKey = cng.DeriveKeyMaterial(bobkey);
using (var aes = new AesCryptoServiceProvider())
{
aes.Key = sumKey;
aes.GenerateIV();
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
using (MemoryStream ms = new MemoryStream())
{
var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
ms.Write(aes.IV, 0, aes.IV.Length);
cs.Write(rowData, 0, rowData.Length);
cs.Close();
var data = ms.ToArray();
Console.WriteLine("Anli send message to bob");
BobReceivesData(data);
}
aes.Clear();
}
}
}
}
}
public static void BobReceivesData(byte[] data)
{
Console.WriteLine("Get the message, to encrypt");
byte[] rowData = null;
using (var aes = new AesCryptoServiceProvider())
{
var ivlength = aes.BlockSize >> 3;
byte[] ivdata = new byte[ivlength];
Array.Copy(data, ivdata, ivlength);
using (ECDiffieHellmanCng cng = new ECDiffieHellmanCng(bobkey))
{
using (CngKey anikey = CngKey.Import(anlipulicKey, CngKeyBlobFormat.EccPublicBlob))
{
var sumKey = cng.DeriveKeyMaterial(anikey);
aes.Key = sumKey;
aes.IV = ivdata;
using (ICryptoTransform decryptor = aes.CreateDecryptor())
using (MemoryStream me = new MemoryStream())
{
var cs = new CryptoStream(me, decryptor, CryptoStreamMode.Write);
cs.Write(data, ivlength, data.Length - ivlength);
cs.Close();
rowData = me.ToArray();
Console.WriteLine("Decrypt successfully!");
Console.WriteLine(Encoding.UTF8.GetString(rowData));
}
}
}
}
}
}
}
最好的问候,
Wendy
这篇关于AesCng持久化密钥导出/导入:导入失败,出现CryptographicException:提供的句柄无效。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!