提供 MSDN 官方 RSA 範例的完整可編譯程式碼,示範金鑰產生、匯出/匯入參數、加密/解密、簽名/驗證全流程,採用 RSA + RC2 混合加密模式 (教學用,現代建議 AES)。
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Microsoft.Samples.Security.PublicKey
{
class App
{
static void Main()
{
var alice = new Person("Alice");
var bob = new Person("Bob");
var steve = new Person("Steve");
CipherMessage aliceMsg, bobMsg, steveMsg;
// 1. 自我加密解密
Console.WriteLine("=== 自我加密解密 ===");
aliceMsg = alice.EncryptMessage("Alice wrote this message");
alice.DecryptMessage(aliceMsg);
// 2. 金鑰交換與通訊
Console.WriteLine("\n=== 金鑰交換 ===");
bob.GetPublicKey(alice);
steve.GetPublicKey(alice);
bobMsg = bob.EncryptMessage("Hi Alice! - Bob");
steveMsg = steve.EncryptMessage("How are you? - Steve");
alice.DecryptMessage(bobMsg);
alice.DecryptMessage(steveMsg);
// 3. 私鑰必要性驗證
Console.WriteLine("\n=== 私鑰驗證 ===");
steve.DecryptMessage(bobMsg); // 失敗
bob.DecryptMessage(bobMsg); // 失敗 (無私鑰無法解開 RC2 金鑰)
}
}
class CipherMessage
{
public byte[] CipherBytes; // RC2 加密資料
public byte[] Rc2Key; // RSA 加密的 RC2 金鑰
public byte[] Rc2IV; // RC2 IV
}
class Person
{
private readonly RSA _rsa = RSA.Create();
private readonly RC2CryptoServiceProvider _rc2 = new RC2CryptoServiceProvider { KeySize = 128 };
private readonly string _name;
public Person(string name) => _name = name;
public RSAParameters SendPublicKey() => _rsa.ExportParameters(false);
public void GetPublicKey(Person other) => _rsa.ImportParameters(other.SendPublicKey());
public CipherMessage EncryptMessage(string text)
{
var msg = new CipherMessage();
byte[] plain = Encoding.Unicode.GetBytes(text);
_rc2.GenerateKey(); _rc2.GenerateIV();
msg.Rc2IV = _rc2.IV;
msg.Rc2Key = _rsa.Encrypt(_rc2.Key, false); // RSA 加密 RC2 金鑰
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, _rc2.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(plain, 0, plain.Length);
cs.FlushFinalBlock();
msg.CipherBytes = ms.ToArray();
}
return msg;
}
public void DecryptMessage(CipherMessage msg)
{
_rc2.IV = msg.Rc2IV;
_rc2.Key = _rsa.Decrypt(msg.Rc2Key, false); // RSA 解密 RC2 金鑰
using (var ms = new MemoryStream(msg.CipherBytes))
using (var cs = new CryptoStream(ms, _rc2.CreateDecryptor(), CryptoStreamMode.Read))
{
byte[] plain = new byte[msg.CipherBytes.Length];
int len = cs.Read(plain, 0, plain.Length);
Console.WriteLine($"{_name} received: {Encoding.Unicode.GetString(plain, 0, len)}");
}
}
}
}
| 項目 | 範例 (舊) | 現代建議 |
|---|---|---|
| 對稱演算法 | RC2 (已淘汰、弱) | AES-256-GCM (`AesGcm` .NET 6+) / AES-CBC + HMAC |
| RSA Padding | PKCS#1 v1.5 (`false`) | OAEP-SHA256 (`RSAEncryptionPadding.OaepSHA256`) |
| 金鑰長度 | 128-bit RC2 | 256-bit AES 金鑰 |
| 認證加密 | 無 | AES-GCM / ChaCha20-Poly1305 內建認證標籤 |
教學理解原理用此碼足矣;生產環境請直接使用 `AesGcm` + `RSA` (OAEP) 或成熟庫 (libsodium-net、BouncyCastle、NSec.Cryptography)。