介紹
重新想象 Windows 8 Store Apps 之 加密解密
非對稱演算法(RSA)
簽名和驗證簽名 (RSA)
通過 CryptographicBuffer 來實現 string hex base64 binary 間的相互轉換
樣本
1、 示範如何使用非對稱演算法(RSA)
Crypto/Asymmetric.xaml.cs
/* * 示範如何使用非對稱演算法(RSA) */ using System;using Windows.Security.Cryptography;using Windows.Security.Cryptography.Core;using Windows.Storage.Streams;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls; namespace XamlDemo.Crypto{ public sealed partial class Asymmetric : Page { public Asymmetric() { this.InitializeComponent(); } private void btnDemo_Click(object sender, RoutedEventArgs e) { string plainText = "i am webabcd"; uint keySize = 2048; lblMsg.Text = "原文: " + plainText; lblMsg.Text += Environment.NewLine; lblMsg.Text += "keySize: " + keySize / 8; lblMsg.Text += Environment.NewLine; lblMsg.Text += Environment.NewLine; string[] algorithmNames = { "RSA_PKCS1", "RSA_OAEP_SHA1", "RSA_OAEP_SHA256", "RSA_OAEP_SHA384", "RSA_OAEP_SHA512" }; foreach (var algorithmName in algorithmNames) { /* * 對於 RSA 非對稱式加密來說,其對原文的長度是有限制的,所以一般用 RSA 來加密對稱演算法的密鑰 * * RSA_PKCS1 要求原文長度 <= 密鑰長度 - 3,單位:位元組 * OAEP 要求原文長度 <= 密鑰長度 - 2 * HashBlock - 2,單位:位元組 * RSA_OAEP_SHA1 - 密鑰長度為 1024 時,最大原文長度 1024 / 8 - 2 * 20 - 2 = 90 * RSA_OAEP_SHA256 - 密鑰長度為 1024 時,最大原文長度 1024 / 8 - 2 * (256 / 8) - 2 = 66 * RSA_OAEP_SHA384 - 密鑰長度為 2048 時,最大原文長度 2048 / 8 - 2 * (384 / 8) - 2 = 162 * RSA_OAEP_SHA512 - 密鑰長度為 2048 時,最大原文長度 2048 / 8 - 2 * (512 / 8) - 2 = 130 */ IBuffer buffer; // 原文 IBuffer encrypted; // 加密後 IBuffer decrypted; // 解密後 IBuffer blobPublicKey; // 公開金鑰 IBuffer blobKeyPair; // 公開金鑰私密金鑰對 CryptographicKey keyPair; // 公開金鑰私密金鑰對 // 原文的位元據 buffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8); // 根據演算法名稱執行個體化一個非對稱演算法提供者 AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName); try { // 根據密鑰長度隨機建立一個公開金鑰私密金鑰對 keyPair = asymmetricAlgorithm.CreateKeyPair(keySize); } catch (Exception ex) { lblMsg.Text += ex.ToString(); lblMsg.Text += Environment.NewLine; return; } // 加密資料(通過公開金鑰) encrypted = CryptographicEngine.Encrypt(keyPair, buffer, null); // 加密後的結果 lblMsg.Text += algorithmName + " encrypted: " + CryptographicBuffer.EncodeToHexString(encrypted) + " (" + encrypted.Length + ")"; lblMsg.Text += Environment.NewLine; // 匯出公開金鑰 blobPublicKey = keyPair.ExportPublicKey(); // 匯出公開金鑰私密金鑰對 blobKeyPair = keyPair.Export(); // 匯入公開金鑰 CryptographicKey publicKey = asymmetricAlgorithm.ImportPublicKey(blobPublicKey); // 匯入公開金鑰私密金鑰對 CryptographicKey keyPair2 = asymmetricAlgorithm.ImportKeyPair(blobKeyPair); // 解密資料(通過私密金鑰) decrypted = CryptographicEngine.Decrypt(keyPair2, encrypted, null); // 解密後的結果 lblMsg.Text += algorithmName + " decrypted: " + CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted); lblMsg.Text += Environment.NewLine; lblMsg.Text += Environment.NewLine; } } }}