我试图使用名为KeyExchange的公用类将.NET RSAPKCS1KeyExchangeFormatter类的示例从https://msdn.microsoft.com/EN-US/library/8kkwbeez(v=VS.110,d=hv.2).aspx拆分为2个控制台应用程序(Alice,Bob)。该类包含两种方法: GenerateEncryptedSessionKeyAndIV:在Alice上运行,加密会话密钥,并用于测试目的对其进行解密。 ProcessEncryptedSessionKeyAndIV:在Bob上运行,未能用Exception“The parameter is incorrect”解密会话密钥。尽管字节数组看起来是正确的。请帮忙。.NET RSAPKCS1KeyExchangeFormatter类 - 异常“参数不正确”
public KeyExchange()
{
rsaKey = new RSACryptoServiceProvider(); // asymmetric encryption/decryption
aes = new AesCryptoServiceProvider(); // symmetric encryption/decryption
}
public byte[] PublicKey
{
get { return rsaKey.ExportCspBlob(false); } // used by partner who wants to send secret session key
set { rsaKey.ImportCspBlob(value); } // used by partner who receives secret session key
}
public void GenerateEncryptedSessionKeyAndIV(out byte[] iv, out byte[] encryptedSessionKey)
{
iv = aes.IV; // Gets the initialization vector (IV) for the symmetric algorithm.
// Encrypt the session key
RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaKey); // Initializes a new instance of the RSAPKCS1KeyExchangeFormatter class with the specified key.
encryptedSessionKey = keyFormatter.CreateKeyExchange(aes.Key, typeof(Aes)); // Create and return the encrypted key exchange data
// test only: the next 2 lines are to prove that the secret key can be obtained from the the encrypted key exchange data here on Alice,
// the same code failes executed on Bob (see method ProcessEncryptedSessionKeyAndIV)
RSAPKCS1KeyExchangeDeformatter keyDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsaKey);
byte[] helper = keyDeformatter.DecryptKeyExchange(encryptedSessionKey);
}
public void ProcessEncryptedSessionKeyAndIV(byte[] iv, byte[] encryptedSessionKey)
{
aes.IV = iv; // Sets the initialization vector (IV) for the symmetric algorithm.
// Decrypt the session key, Create a KeyExchangeDeformatter
RSAPKCS1KeyExchangeDeformatter keyDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsaKey);
// obtain the secret key (32 bytes) from from the encrypted key exchange data (128 bytes)
aes.Key = keyDeformatter.DecryptKeyExchange(encryptedSessionKey); // this results in CryptographicException: The parameter is incorrect.
}
堆栈跟踪会很有用。 – bartonjs