我有公钥模数和公钥指数,我需要在metro风格的应用程序中生成公钥并加密数据.在c#中我们有RSAParameters类,但我找不到任何类似于metro风格应用程序的东西.
当我使用从证书直接接收的base64encoded公钥并尝试使用以下代码导入密钥时,我得到异常抛出的ASN1错误标记值.
我认为这是由于数据格式无效.
//sample dummy key from certificate in base64encoded
string key = @"MIIB0zCCAX2gAwIBAgIJAMF/bHcA799IMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwHhcNMTIwMzI3MTEyNjQ5WhcNMTMwMzI3MTEyNjQ5WjBFMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMEPeWjP4sdqxvBlDId4BtRRTeWPwjlZLSOFvOVgmoSyoPva8psFUF6tH9/vPXIJrL80tdCoBt8YFH6pwDN9a1sCAwEAAaNQME4wHQYDVR0OBBYEFGARqQfUhX7atVU4sS+aQAPt/jFxMB8GA1UdIwQYMBaAFGARqQfUhX7atVU4sS+aQAPt/jFxMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADQQALqOyjovRbWUZvziVaE8QYy83WEln1l+HJU9D6tFncUZTlwSd8aUwyQsd3zOVNZ41oCAVv5R3h1jtBtPbM+c1K";
symmetricKeyAlgorithmProvider asymmAlg = AsymmetricKeyAlgorithmProvider.OpenAlgorithm("RSA_OAEP_SHA1");
CryptographicKey publicKey = asymmAlg.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(key));
string input64string ="encrypt this";
IBuffer dataToEncrypt = CryptographicBuffer.DecodeFromBase64String(input64string);
IBuffer encryptedData = CryptographicEngine.Encrypt(publicKey, dataToEncrypt, null);
最佳答案 您的密钥是公钥的模数部分,其长度为128.考虑从Metro中的C#代码导出的标准密钥:
using System.Runtime.InteropServices.WindowsRuntime;
CryptographicKey standardKeyPair = provider.CreateKeyPair(1024);
byte[] standardKey = standardKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey).ToArray();
你可以看到byte [] standardKey的长度是140,它有7位前缀和5位尾.我不知道原因,但我将额外的12位复制到已知密钥,它可以工作.希望这可以帮助你:
public static IBuffer RsaEncrypt(this IBuffer dataToEncrypt, string publicKeyN)
{
AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
CryptographicKey standardKeyPair = provider.CreateKeyPair(1024);
byte[] standardKey = standardKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey).ToArray();
var data_n = CryptographicBuffer.DecodeFromBase64String(publicKeyN).ToArray();
Array.Copy(data_n, 0, standardKey, 7, data_n.Length);
var key = provider.ImportPublicKey(standardKey.AsBuffer(), CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
var result = CryptographicEngine.Encrypt(key, dataToEncrypt, null);
return result;
}