c# - 使用 RSA 编码字符串

标签 c# encryption rsa

我正在使用一个 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/

相关文章:

c# - .net(或至少是 c#)是否有任何安全的重构工具?

php - 加密/解密文件

encryption - 使用部分私钥审查来解密 RSA 消息?

c# - 如何使用 C# 获取 Active Directory 中的部门列表

c# - 查找具有相同内部表示的 float / double 的最小值/最大值

forms - 您在连接字符串中指定了密码,但您使用的 native SQLite 库不支持加密

c++ - 从 WinHTTP 中的 CRYPT_BIT_BLOB 获取 RSA 公钥?

c# - 使用 RSA SHA 256 对字符串进行签名,仅使用私钥作为字符串 .NET

c - OpenSSL rsa 例程 :RSA_padding_check_PKCS1_type_2:pkcs decoding error

c# - 确定对象是否派生自集合类型