我正在尝试将此方法从 .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;
}
但是它不起作用。
为了获得与我的桌面应用程序相同的功能...
我应该将什么
AmetryAlgorithmNames
传递给OpenAlgorithm()
?我应该将什么
CryptographicPublicKeyBlobType
传递给ImportPublicKey()
?
最佳答案
根据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);
}
如果重要的话,这就是我生成非对称 key 的方式:http://43n141e.blogspot.co.uk/2008/08/rsa-encryption-openssl-to-ruby-to-c-and_27.html
关于c# - 根据公钥指数/模数进行 WinRT RSA 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17210175/