本文整理汇总了C#中System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter类的典型用法代码示例。如果您正苦于以下问题:C# RSAPKCS1KeyExchangeDeformatter类的具体用法?C# RSAPKCS1KeyExchangeDeformatter怎么用?C# RSAPKCS1KeyExchangeDeformatter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RSAPKCS1KeyExchangeDeformatter类属于System.Security.Cryptography命名空间,在下文中一共展示了RSAPKCS1KeyExchangeDeformatter类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class Alice
{
public static void Main(string[] args)
{
using (Bob bob = new Bob())
{
using (RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider())
{
// Get Bob's public key
rsaKey.ImportCspBlob(bob.key);
byte[] encryptedSessionKey = null;
byte[] encryptedMessage = null;
byte[] iv = null;
Send(rsaKey, "Secret message", out iv, out encryptedSessionKey, out encryptedMessage);
bob.Receive(iv, encryptedSessionKey, encryptedMessage);
}
}
}
private static void Send(RSA key, string secretMessage, out byte[] iv, out byte[] encryptedSessionKey, out byte[] encryptedMessage)
{
using (Aes aes = new AesCryptoServiceProvider())
{
iv = aes.IV;
// Encrypt the session key
RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(key);
encryptedSessionKey = keyFormatter.CreateKeyExchange(aes.Key, typeof(Aes));
// Encrypt the message
using (MemoryStream ciphertext = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] plaintextMessage = Encoding.UTF8.GetBytes(secretMessage);
cs.Write(plaintextMessage, 0, plaintextMessage.Length);
cs.Close();
encryptedMessage = ciphertext.ToArray();
}
}
}
}
public class Bob : IDisposable
{
public byte[] key;
private RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
public Bob()
{
key = rsaKey.ExportCspBlob(false);
}
public void Receive(byte[] iv, byte[] encryptedSessionKey, byte[] encryptedMessage)
{
using (Aes aes = new AesCryptoServiceProvider())
{
aes.IV = iv;
// Decrypt the session key
RSAPKCS1KeyExchangeDeformatter keyDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsaKey);
aes.Key = keyDeformatter.DecryptKeyExchange(encryptedSessionKey);
// Decrypt the message
using (MemoryStream plaintext = new MemoryStream())
using (CryptoStream cs = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(encryptedMessage, 0, encryptedMessage.Length);
cs.Close();
string message = Encoding.UTF8.GetString(plaintext.ToArray());
Console.WriteLine(message);
}
}
}
public void Dispose()
{
rsaKey.Dispose();
}
}