private void btnAsymmEncrypt_Click(object sender, EventArgs e) { AsymmetricCrypto crypto = new AsymmetricCrypto(); // 產生公鑰與私鑰 AsymmetricCrypto.PublicKey pubKey = new AsymmetricCrypto.PublicKey(); AsymmetricCrypto.PrivateKey priKey = new AsymmetricCrypto.PrivateKey(); crypto.GenerateNewKeyset(ref pubKey, ref priKey); // 用公鑰加密 ByteArray inputData = new ByteArray(txtRawData.Text); ByteArray encrypted = crypto.Encrypt(inputData, pubKey); txtAsymmEncrypted.Text = encrypted.Base64String; // 用私鑰解密 ByteArray decrypted = crypto.Decrypt(encrypted, priKey); txtAsymmDecrypted.Text = decrypted.Text; }
public void AsymmetricCrypto_RsaEncryption() { string privateKey; string publicKey; byte[] plainText = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; byte[] encrypted; byte[] decrypted; try { privateKey = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024); publicKey = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey); encrypted = AsymmetricCrypto.Encrypt(CryptoAlgorithm.RSA, publicKey, plainText); CollectionAssert.AreNotEqual(encrypted, plainText); decrypted = AsymmetricCrypto.Decrypt(CryptoAlgorithm.RSA, privateKey, encrypted); CollectionAssert.AreEqual(plainText, decrypted); encrypted = AsymmetricCrypto.Encrypt(CryptoAlgorithm.RSA, privateKey, plainText); Assert.AreNotEqual(encrypted, plainText); decrypted = AsymmetricCrypto.Decrypt(CryptoAlgorithm.RSA, privateKey, encrypted); CollectionAssert.AreEqual(plainText, decrypted); AsymmetricCrypto.SaveKey(CryptoAlgorithm.RSA, KeyContainer, null, privateKey); encrypted = AsymmetricCrypto.Encrypt(CryptoAlgorithm.RSA, KeyContainer, plainText); CollectionAssert.AreNotEqual(encrypted, plainText); decrypted = AsymmetricCrypto.Decrypt(CryptoAlgorithm.RSA, KeyContainer, encrypted); CollectionAssert.AreEqual(plainText, decrypted); encrypted = AsymmetricCrypto.Encrypt(CryptoAlgorithm.RSA, KeyContainer, plainText); CollectionAssert.AreNotEqual(encrypted, plainText); decrypted = AsymmetricCrypto.Decrypt(CryptoAlgorithm.RSA, KeyContainer, encrypted); CollectionAssert.AreEqual(plainText, decrypted); } finally { AsymmetricCrypto.DeleteKey(CryptoAlgorithm.RSA, KeyContainer, null); } }