首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 標準加密演算法實作範例 (三) - RSA 完整程式碼 (MSDN 範例)

     編輯:關於C語言

提供 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)}");
            }
        }
    }
}

關鍵流程說明

  1. 混合加密:RSA 只加密 RC2 對稱金鑰 (128-bit),資料本體由 RC2 加密。現代請換為 AES-256-GCM。
  2. 金鑰交換:`GetPublicKey` 匯入對方公開參數,`SendPublicKey` 匯出自己的公開參數 (不含私鑰)。
  3. 私鑰保護:`_rsa` 實例內含私鑰,僅持有者能解密 `Rc2Key` 並進而解密資料。
  4. IV 公開傳輸:初始化向量無需保密,但每次加密必須隨機產生。

現代化建議 (替代 RC2)

項目範例 (舊)現代建議
對稱演算法RC2 (已淘汰、弱)AES-256-GCM (`AesGcm` .NET 6+) / AES-CBC + HMAC
RSA PaddingPKCS#1 v1.5 (`false`)OAEP-SHA256 (`RSAEncryptionPadding.OaepSHA256`)
金鑰長度128-bit RC2256-bit AES 金鑰
認證加密無AES-GCM / ChaCha20-Poly1305 內建認證標籤

教學理解原理用此碼足矣;生產環境請直接使用 `AesGcm` + `RSA` (OAEP) 或成熟庫 (libsodium-net、BouncyCastle、NSec.Cryptography)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved