公钥指数/模数的WinRT RSA加密

时间:2013-06-20 09:31:44

标签: c# windows-runtime microsoft-metro rsa

我正在尝试将此方法从.NET 4.5桌面应用程序移植到WinRT应用程序:

static byte[] DotNetRsaEncrypt(string modulus, string exponent, byte[] data)
{
    var modulusBytes = Convert.FromBase64String(modulus);
    var exponentBytes = Convert.FromBase64String(exponent);

    var rsaParameters = new RSAParameters { Modulus = modulusBytes, Exponent = exponentBytes };
    var rsa = new RSACryptoServiceProvider();
    rsa.ImportParameters(rsaParameters);

    var encrypted = rsa.Encrypt(data, true);
    return encrypted;
}

阅读此RSA Encryption in metro style Application

我尝试了以下内容:

static byte[] WinRtRsaEncrypt(string modulus, string exponent, byte[] data)
{        
    var modulusBytes = Convert.FromBase64String(modulus);
    var exponentBytes = Convert.FromBase64String(exponent);

    var keyBlob = modulusBytes.Concat(exponentBytes).ToArray().AsBuffer();

    var rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha1);
    var key = rsa.ImportPublicKey(keyBlob, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);

    var encrypted = CryptographicEngine.Encrypt(key, data.AsBuffer(), null);
    return encrypted;
}

但它不起作用。

为了获得与桌面应用程序相同的功能......

  • 我应该将AsymmetricAlgorithmNames传递给OpenAlgorithm()

  • 我应该将CryptographicPublicKeyBlobType传递给ImportPublicKey()

2 个答案:

答案 0 :(得分:2)

跟进user1968335的提示,这对我有用。

首先,在C#应用程序中,使用以下代码从模数/指数中获取CspBlob:

var exponent = Encoding.Default.GetBytes(exponentStr);
var modulus = Encoding.Default.GetBytes(modulusStr);

var rsaParameters = new RSAParameters { Modulus = modulus, Exponent = exponent };
var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
var cspBlobString = Convert.ToBase64String(rsa.ExportCspBlob(false)); 

然后,在WinRT应用程序中,您可以使用该CspBlob对这样的数据进行签名:

private static string SignString(string data)
{
    string cspBlobString = //cspBlob
    var keyBlob = CryptographicBuffer.DecodeFromBase64String(cspBlobString);

    AsymmetricKeyAlgorithmProvider rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
    CryptographicKey key = rsa.ImportPublicKey(keyBlob, CryptographicPublicKeyBlobType.Capi1PublicKey);

    IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);
    IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);

    byte[] encryptedBytes;
    CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedBytes);

    return Convert.ToBase64String(encryptedBytes);
}

如果重要,这就是我生成非对称密钥的方式:http://43n141e.blogspot.co.uk/2008/08/rsa-encryption-openssl-to-ruby-to-c-and_27.html

答案 1 :(得分:0)

根据CryptoWinRT sampleOpenAlgorithm(...)方法采用这些值。

  • RSA_PKCS1
  • RSA_OAEP_SHA1
  • RSA_OAEP_SHA256
  • RSA_OAEP_SHA384

另请参阅:RSA cryptography between a WinRT and a .Net app