2

我正在尝试将此方法从 .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;
}

在以 Metro 风格应用程序阅读此RSA 加密之后

我尝试了以下方法:

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()什么?

4

2 回答 2

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

于 2013-09-09T22:28:06.757 回答
0

根据CryptoWinRT 示例OpenAlgorithm(...)方法采用这些值。

  • RSA_PKCS1
  • RSA_OAEP_SHA1
  • RSA_OAEP_SHA256
  • RSA_OAEP_SHA384

另请参阅:WinRT 和 .Net 应用程序之间的 RSA 加密

于 2013-06-20T11:00:44.787 回答