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SHqO0Koso6xrLzrN42/b32oLxmFOwEWAcfDlJ6sEWT0KS/X0FSY/SHbrBZVVwB43gN7QNGvnh22Dek3LicawxYEwvTTjfdbf9K0b/iiLtQoVRfaC7nwm4bBGc1xSImo4upaXN+jLXtw3aK9/JBC2azZncSv+4NJWNSYlSHC4uk36PZqCKl6zly/MS4dPwSJbcovAGd24TQiKRXbw==
解密消息: Hello, this is a secret message!
ECC 公钥: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvB5M2an/YkzomTxEA1uZcy696O7xk3u/Dz0i7IrcB+1B12WrHtqJrRgKeePHVeg94Y+dxkJ3PrdcLKn51/qJaw==
ECC 私钥: MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgx3KL5Xiv+/ZQZNWwhLYeEw6Tp5r/mYI6msI/j1vnvQmgCgYIKoZIzj0DAQehRANCAAS8HkzZqf9iTOiZPEQDW5lzLr3o7vGTe78PPSLsitwH7UHXZase2omtGAp548dV6D3hj53GQnc+t1wsqfnX+olr
加密消息: BP0dLeL78X41WQU1McMSvqxmZBRkVSPitHW1/jkMx5mVb5p3DNBqd17KP4HRjGDCOq4JB2bavyp6vTm+3czbXw3aVzTNMCGcSnlzgHGXVUP0b14wNCZotTfNlwB88Oh0KlK19Bk4ShElHONH5Ah8zW9efU3O
解密消息: Hello, this is a secret message!
2.C#中的使用
2.1. 原生使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;namespace ConsoleSymmetricEncryption
{public class RSAExample{public static void RSADemo(){using (RSA rsa = RSA.Create()){// 导出公钥和私钥var publicKey = rsa.ExportRSAPublicKey();var privateKey = rsa.ExportRSAPrivateKey();string originalMessage = "Hello, RSA! 小菜";byte[] messageBytes = Encoding.UTF8.GetBytes(originalMessage);// 加密byte[] encryptedMessage = rsa.Encrypt(messageBytes, RSAEncryptionPadding.Pkcs1);string encryptedText = Convert.ToBase64String(encryptedMessage);// 解密byte[] decryptedMessage = rsa.Decrypt(encryptedMessage, RSAEncryptionPadding.Pkcs1);string decryptedText = Encoding.UTF8.GetString(decryptedMessage);Console.WriteLine($"encryptedText: {encryptedText}");Console.WriteLine($"decryptedText: {decryptedText}");}}}}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;namespace ConsoleSymmetricEncryption
{public class ECCExample{public static void ECCSignDemo(){using (ECDsa ecdsa = ECDsa.Create()){// 生成密钥对byte[] publicKey = ecdsa.ExportSubjectPublicKeyInfo();byte[] privateKey = ecdsa.ExportECPrivateKey();string originalMessage = "Hello, ECC!";byte[] messageBytes = Encoding.UTF8.GetBytes(originalMessage);// 签名byte[] signature = ecdsa.SignHash(SHA256.HashData(messageBytes));// 验证签名bool isValid = ecdsa.VerifyHash(SHA256.HashData(messageBytes), signature);Console.WriteLine($"Original Message: {originalMessage}");Console.WriteLine($"Is Signature Valid: {isValid}");}}public static void ECCDemo(){// Alice 和 Bob 各自生成 ECC 密钥对using (ECDiffieHellmanCng bob = new ECDiffieHellmanCng()){ECDiffieHellmanCng alice = new ECDiffieHellmanCng();alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;alice.HashAlgorithm = CngAlgorithm.Sha256;bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;bob.HashAlgorithm = CngAlgorithm.Sha256;// Alice 获取 Bob 的公钥,生成共享密钥byte[] alicePublicKey = bob.PublicKey.ToByteArray();byte[] aliceSharedKey = alice.DeriveKeyMaterial(CngKey.Import(alicePublicKey, CngKeyBlobFormat.EccPublicBlob));// Bob 获取 Alice 的公钥,生成共享密钥byte[] bobPublicKey = alice.PublicKey.ToByteArray();byte[] bobSharedKey = bob.DeriveKeyMaterial(CngKey.Import(bobPublicKey, CngKeyBlobFormat.EccPublicBlob));// 确保 Alice 和 Bob 生成的共享密钥是相同的Console.WriteLine($"Alice's Shared Key: {Convert.ToBase64String(aliceSharedKey)}");Console.WriteLine($"Bob's Shared Key: {Convert.ToBase64String(bobSharedKey)}");Console.WriteLine($"Keys are equal: {Convert.ToBase64String(aliceSharedKey) == Convert.ToBase64String(bobSharedKey)}");// 使用共享密钥进行 AES 加密和解密string originalMessage = "Hello, ECC with AES!";byte[] encryptedMessage = AESEncrypt(originalMessage, aliceSharedKey);string decryptedMessage = AESDecrypt(encryptedMessage, bobSharedKey);Console.WriteLine($"Original Message: {originalMessage}");Console.WriteLine($"Decrypted Message: {decryptedMessage}");}}// AES 加密方法private static byte[] AESEncrypt(string plainText, byte[] key){using (Aes aes = Aes.Create()){aes.Key = key;aes.GenerateIV(); // 随机生成 IVusing (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV)){byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);// 返回 IV 和加密的数据byte[] result = new byte[aes.IV.Length + encryptedBytes.Length];Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);Array.Copy(encryptedBytes, 0, result, aes.IV.Length, encryptedBytes.Length);return result;}}}// AES 解密方法private static string AESDecrypt(byte[] encryptedData, byte[] key){using (Aes aes = Aes.Create()){aes.Key = key;// 提取 IVbyte[] iv = new byte[aes.BlockSize / 8];byte[] cipherText = new byte[encryptedData.Length - iv.Length];Array.Copy(encryptedData, iv, iv.Length);Array.Copy(encryptedData, iv.Length, cipherText, 0, cipherText.Length);aes.IV = iv;using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV)){byte[] decryptedBytes = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);return Encoding.UTF8.GetString(decryptedBytes);}}}}
}
encryptedText: Q8TCZh5f6u8dOSRYigreS2DIUy4fLV8pQlaklqi3pcz5zm7ZYX4p2d3fHYE7hKMmyvqYiZxSL+q4MyMJX8rKxgF94Q0Ba25Sa3RxHSbgAM3fkREnn9eS5cK+xk2kCX/tqsHl4ZT/6zTBoiHugec9eta7J+1zEblyEbprHbCe2SXLJDd64TbqqZTF7qo6OSyMcwP5v9PJHb1zSdLuDeHvfP7Uwydvrq9TdPZH3Bc0LnJElb8oEdCaFYRlMYCcRfs1gu0rnUpCl7ELUvZ+jxgcb4Xnup/jzoZfRamvvEM3f4tEHLiOCVkyAw729RavXJhsgWrj55liqgOP0dnbDqn0kA==
decryptedText: Hello, RSA! 小菜
Original Message: Hello, ECC!
Is Signature Valid: True
Alice's Shared Key: FEmE+ZdiM68D/XRMquoNzWWBjcorVYannZ+xoVXTh5U=
Bob's Shared Key: FEmE+ZdiM68D/XRMquoNzWWBjcorVYannZ+xoVXTh5U=
Keys are equal: True
Original Message: Hello, ECC with AES!
Decrypted Message: Hello, ECC with AES!
2.2.库Bouncy Castle实现
using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Security;public class RSAWithBouncyCastleExample
{public static void RSAWithBouncyCastleDemo(){// 生成 RSA 密钥对AsymmetricCipherKeyPair keyPair = GenerateRSAKeyPair();var publicKey = (RsaKeyParameters)keyPair.Public;var privateKey = (RsaKeyParameters)keyPair.Private;// 要加密的原始信息string originalMessage = "Hello, RSA with Bouncy Castle!";byte[] messageBytes = Encoding.UTF8.GetBytes(originalMessage);// 使用公钥加密byte[] encryptedData = Encrypt(messageBytes, publicKey);Console.WriteLine($"Encrypted Data: {Convert.ToBase64String(encryptedData)}");// 使用私钥解密byte[] decryptedData = Decrypt(encryptedData, privateKey);string decryptedMessage = Encoding.UTF8.GetString(decryptedData);Console.WriteLine($"Decrypted Message: {decryptedMessage}");}// 生成 RSA 密钥对public static AsymmetricCipherKeyPair GenerateRSAKeyPair(){var keyGenerationParameters = new KeyGenerationParameters(new SecureRandom(), 2048); // 2048位密钥var keyPairGenerator = new RsaKeyPairGenerator();keyPairGenerator.Init(keyGenerationParameters);return keyPairGenerator.GenerateKeyPair();}// 使用公钥加密public static byte[] Encrypt(byte[] plainText, RsaKeyParameters publicKey){var engine = new RsaEngine();engine.Init(true, publicKey); // true表示加密return engine.ProcessBlock(plainText, 0, plainText.Length);}// 使用私钥解密public static byte[] Decrypt(byte[] cipherText, RsaKeyParameters privateKey){var engine = new RsaEngine();engine.Init(false, privateKey); // false表示解密return engine.ProcessBlock(cipherText, 0, cipherText.Length);}
}
using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Modes;public class ECCWithAESExample
{public static void ECCWithBouncyCastleDemo(){// 生成 Alice 和 Bob 的 ECC 密钥对var keyPairGenerator = new ECKeyPairGenerator();var keyGenParams = new KeyGenerationParameters(new SecureRandom(), 256);keyPairGenerator.Init(keyGenParams);// Alice 和 Bob 各自生成密钥对AsymmetricCipherKeyPair aliceKeyPair = keyPairGenerator.GenerateKeyPair();AsymmetricCipherKeyPair bobKeyPair = keyPairGenerator.GenerateKeyPair();var alicePublicKey = (ECPublicKeyParameters)aliceKeyPair.Public;var alicePrivateKey = (ECPrivateKeyParameters)aliceKeyPair.Private;var bobPublicKey = (ECPublicKeyParameters)bobKeyPair.Public;var bobPrivateKey = (ECPrivateKeyParameters)bobKeyPair.Private;// 通过密钥交换生成共享密钥byte[] aliceSharedKey = GenerateSharedSecret(alicePrivateKey, bobPublicKey);byte[] bobSharedKey = GenerateSharedSecret(bobPrivateKey, alicePublicKey);// 确保共享密钥相同Console.WriteLine($"Alice Shared Key: {Convert.ToBase64String(aliceSharedKey)}");Console.WriteLine($"Bob Shared Key: {Convert.ToBase64String(bobSharedKey)}");Console.WriteLine($"Keys are equal: {Convert.ToBase64String(aliceSharedKey) == Convert.ToBase64String(bobSharedKey)}");// 使用共享密钥进行 AES 加密和解密string originalMessage = "Hello, ECC with AES!";byte[] encryptedMessage = AESEncrypt(originalMessage, aliceSharedKey);string decryptedMessage = AESDecrypt(encryptedMessage, bobSharedKey);Console.WriteLine($"Original Message: {originalMessage}");Console.WriteLine($"Decrypted Message: {decryptedMessage}");}// 生成共享密钥(ECC 密钥交换)private static byte[] GenerateSharedSecret(ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey){var agreement = new ECDHBasicAgreement();agreement.Init(privateKey);var sharedSecret = agreement.CalculateAgreement(publicKey);return sharedSecret.ToByteArray();}// AES 加密方法private static byte[] AESEncrypt(string plainText, byte[] key){// 截取共享密钥的一部分用于 AES 密钥byte[] aesKey = new byte[16];Array.Copy(key, 0, aesKey, 0, 16);var aesEngine = new AesEngine();var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(aesEngine));cipher.Init(true, new KeyParameter(aesKey));byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);byte[] encryptedBytes = new byte[cipher.GetOutputSize(plainBytes.Length)];int length = cipher.ProcessBytes(plainBytes, 0, plainBytes.Length, encryptedBytes, 0);cipher.DoFinal(encryptedBytes, length);return encryptedBytes;}// AES 解密方法private static string AESDecrypt(byte[] cipherText, byte[] key){byte[] aesKey = new byte[16];Array.Copy(key, 0, aesKey, 0, 16);var aesEngine = new AesEngine();var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(aesEngine));cipher.Init(false, new KeyParameter(aesKey));byte[] decryptedBytes = new byte[cipher.GetOutputSize(cipherText.Length)];int length = cipher.ProcessBytes(cipherText, 0, cipherText.Length, decryptedBytes, 0);cipher.DoFinal(decryptedBytes, length);return Encoding.UTF8.GetString(decryptedBytes).TrimEnd('\0');}
}
Alice Shared Key: AMKHXIMVFLpUalPjkgKJrGtfH2/x9dU47Ls3Ci7Xst15
Bob Shared Key: AMKHXIMVFLpUalPjkgKJrGtfH2/x9dU47Ls3Ci7Xst15
Keys are equal: True
Original Message: Hello, ECC with AES!
Decrypted Message: Hello, ECC with AES!
Encrypted Data: HFZyDohNGBXmx5SXRXc8eHUfd9iw/18AHJRGkgRlANxMGFHX6K4sg3c+6XuYkhiA7tZABl79xhkqW9FPM1Mgkjc2IhYlNMUpdCmvplsvTCtmNnsArc/S2KfZOb7uNqXrw24tNJaFVsbEbgX00FZ94A0ix47PPt2pUTxeqfEfFGMmZaN0Iwe2M8e+os44iY1cHCOiKidKxByOwanrkTvTLEciOyncW0iBkzJR6DcCM8fSaaL1pvkaeVSdoPKIOjANrKLt594DZAGt2xEejR+/KOtNl7W8HDn2qSUGmACrTR9wfMzT67zW67Pz2Kb4UiOjekBYANnmSenHZOgWsrjVHQ==
Decrypted Message: Hello, RSA with Bouncy Castle!