Windows 8 Store Apps学习(32) 加密解密: 非对称算法, 数据转换的辅助类2013-12-06 cnblogs webabcd介绍重新想象 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;}}}}