AsymmetricKeyAlgorithmProvider Import

2019-09-14 02:49发布

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.

I already found a Solution with Chilkat's Rsa Class. But this is no freeware unfortunately. Alternatives?

Thanks!

1条回答
祖国的老花朵
2楼-- · 2019-09-14 03:17

How can I Import my Public/Private Key to AsymmetricKeyAlgorithmProvider's ImportKeyPair-Method? How do I have to create the IBuffer parameter?

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);

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];
    }
}
查看更多
登录 后发表回答