我正在使用一个 API,该 API 指定必须使用“RSA/ECB/PKCS1Padding”编码传递某些文本。公钥以 .PEM 格式提供;我认为我已成功将其转换为 XML 格式,并且我现在正在使用以下 C# 代码:
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider();
rsa1.FromXmlString(testpublickey);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] textBytes = encoding.GetBytes(plainstring);
byte[] encryptedOutput = rsa1.Encrypt(textBytes, false);
string outputB64 = Convert.ToBase64String(encryptedOutput);
Console.WriteLine(outputB64);
return outputB64;
但是,返回的字符串与预期不匹配 - API 给出了以下 OpenSSL 命令作为示例:
openssl rsautl -encrypt -in PIN.txt -inkey public_key_for_pin.pem -pubin | openssl base64 > PIN.base64
OpenSSL 的输出与我的代码的输出不匹配。任何人都可以看到我的代码有什么问题吗?我是否需要指定特定的填充,或者我是否可能在从 PEM 到 XML 的转换中破坏了公钥文件?
最佳答案
我这样做是为了使用公钥加密数据。
首先将PEM数据加载到X509Certificate2
类中,它有可以使用的Import方法。
然后我使用下面的代码:
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography;
public static string EncryptString(string clearText, X509Certificate2 cert)
{
try
{
byte[] encodedCypher = EncryptData(Encoding.UTF8.GetBytes(clearText), cert);
string cipherText = Convert.ToBase64String(encodedCypher);
return cipherText;
}
catch (Exception ex)
{
throw new EncryptionException("Could not Encrypt String. See InnerException for details.", ex);
}
}
private static byte[] EncryptData(byte[] clearText, X509Certificate2 cert)
{
ContentInfo payloadInfo = new ContentInfo(clearText);
EnvelopedCms payloadEnvelope = new EnvelopedCms(payloadInfo);
CmsRecipient certHandle = new CmsRecipient(cert);
payloadEnvelope.Encrypt(certHandle);
return payloadEnvelope.Encode();
}
关于c# - 使用 RSA 编码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167449/