gpt4 book ai didi

c# - 来自公钥指数/模数的 WinRT RSA 加密

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:25 26 4
gpt4 key购买 nike

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

最佳答案

根据 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com