因项目上需要用到,之前在WP8.0的环境上调试通过,现在在开发8.1时发现已不支持原来的加密库,所以无法使用以前的方法,不得已,去寻找windows命名空间下RSA的加解密方法,经过几天的尝试,将解决方案贴出来,看能否帮助碰到如此类型的问题的同学.
本示例的应且场景,服务器端返回RSA的公钥私钥,客户端导入公钥及私钥
服务端:
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivatelKey);//此处为XML格式的私钥,如
//<RSAKeyValue><Modulus>.........Mk=</Modulus><Exponent>AQAB</Exponent><P>....../.....LGAAE=</D></RSAKeyValue>
byte[] data1 = rsa.ExportCspBlob(false); byte[] data2 = rsa.ExportCspBlob(true);String pubkey = System.Convert.ToBase64String(data1);
string privKey = System.Convert.ToBase64String(data2);
WP8.1:
public static byte[] Encrypt(byte[] data, string publicKey){
IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(data, 0, data.Length);
AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm("RSA_PKCS1");
try
{
// 根据算法名称实例化一个非对称算法提供程序
CryptographicKey key = asymmetricAlgorithm.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
IBuffer encrypted = CryptographicEngine.Encrypt(key, buffer, null);
// 加密后的结果
return encrypted.ToArray();
}
catch (Exception er)
{
return new byte[0];}
}
public static byte[] Decrypt(byte[] data, string publicKey, string privateKey){
IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(data, 0, data.Length);
// 根据算法名称实例化一个非对称算法提供程序
AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
try
{
CryptographicKey pubkey = asymmetricAlgorithm.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
// 导入公钥私钥对
CryptographicKey keyPair2 = asymmetricAlgorithm.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(privateKey), CryptographicPrivateKeyBlobType.Capi1PrivateKey);
// 解密数据(通过私钥)
IBuffer decrypted = CryptographicEngine.Decrypt(keyPair2, buffer, null);
return decrypted.ToArray();
}
catch (Exception er)
{
return new byte[0];}