问题描述
我的问题是,在使用UWP-Apps时,我不能使用 RSACryptoServiceProvider
。这意味着我必须使用 CryptographicEngine
来加密/解密数据。如何将我的公钥/私钥导入到 AsymmetricKeyAlgorithmProvider
的 ImportKeyPair
方法?我该如何创建IBuffer参数?我有两个Pem或xml文件,一个用于私有,一个用于公共密钥,我想将其用于加密/解密。它们是在外部创建的。
My problem is that with UWP-Apps I can not use RSACryptoServiceProvider
. That means I have to use CryptographicEngine
to en/decrypt data. How can I Import my Public/Private Key to AsymmetricKeyAlgorithmProvider
's ImportKeyPair
-Method? How do I have to create the IBuffer parameter? I have two Pem or alternatively xml files, one for Private and one for Public key, which I want to use for en/decryption. They are externally created.
我已经找到了Chilkat的 Rsa
类的解决方案。不幸的是,这不是免费软件。备择方案?
I already found a Solution with Chilkat's Rsa
Class. But this is no freeware unfortunately. Alternatives?
谢谢!
推荐答案
在服务器中,您仍然可以使用常规的RSACryptoServiceProvider返回publickey和privatekey。 / p>
In server, you still could use the general RSACryptoServiceProvider to return publickey and privatekey.
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivatelKey);
byte[] data1 = rsa.ExportCspBlob(false);
byte[] data2 = rsa.ExportCspBlob(true);
string pubkey = System.Convert.ToBase64String(data1);
string privKey = System.Convert.ToBase64String(data2);
在UWP应用中,您可以使用AsymmetricKeyAlgorithmProvider加密和解密数据。
In UWP apps, you could use AsymmetricKeyAlgorithmProvider to encrypt and decrypt data.
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 ex)
{
Debug.WriteLine(ex.StackTrace);
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 ex)
{
Debug.WriteLine(ex.StackTrace);
return new byte[0];
}
}
这篇关于AsymmetricKeyAlgorithmProvider导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!