.NET私钥RSA加密

14

我需要使用RSA 1.5算法加密一个字符串。我已经拥有了私钥,但是我无法弄清楚如何将此密钥添加到类中。似乎该密钥必须是RSAParameter结构类型的。然而,这需要一组值,例如模数、指数、P、Q等,但我只有私钥。有人能帮忙吗?


你有关键字吗?显然,你可能不想逐字提供它,但你能再描述一些吗? - Jodrell
请发布您尝试过的内容。老实说,我怀疑您并不理解RSA的工作原理。我不知道您使用的是哪些类,因此无法提供建议。请阅读此文:https://dev59.com/s3M_5IYBdhLWcg3w4njb - Security Hound
1
我收到的密钥看起来像这样-----BEGIN RSA PRIVATE KEY-----MIIadfdafCXdfawIBAAKBgQCIgynd6pvlCF= -----END RSA PRIVATE KEY----- -----BEGIN PUBLIC KEY-----jaz+wadfadIDAQAB -----END PUBLIC KEY----- 这是我所拥有的全部内容。 - Steve Kiss
2个回答

28

你应该了解Bouncycastle C#库。其中有两个非常有用的类:Org.BouncyCastle.OpenSsl.PemReader,它将从openssl样式的密钥转换为bouncycastle密钥对象;Org.BouncyCastle.Security.DotNetUtilities,它将把bouncycastle密钥转换为.NET的RSAParameters对象。

这里是一小段未经测试的代码,展示了如何使用它:

using System;
using System.IO;
using System.Security.Cryptography;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;

namespace RSAOpensslToDotNet
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader("../../privatekey.pem");
            PemReader pr = new PemReader(sr);
            AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
            RSAParameters rsa = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
        }
    }
}

我已经在很多地方寻找这个...谢谢! - MattyP
我需要使用Java完成这个确切的事情。当我使用pr.readObject()时,它返回PEMKeyPair,并在我将其转换为AsymmetricCipherKeyPair时抛出异常。我无论如何都想不明白原因。请帮忙! - C0D3
对我来说引发了一个 InvalidCastException 异常。 - mikerobi
1
@mikerobi:你确定你的密钥文件包含私钥吗? - President James K. Polk
针对在Linux/Docker下使用Bouncy Castle的用户,请参考以下链接:https://github.com/bcgit/bc-csharp/issues/160 - monty

5

我猜这就是你要找的内容:

    // Import ASymmetric RSA Key from a system file.
    public static RSAParameters ImportRSAKey(String fileName)
    {

        // Create a stream to a the specified system file.
        Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        // Extract/Deserialize the key from the file.
        IFormatter soapFormatter = new SoapFormatter();            
        RSAParameters rsaParameter = 
           (RSAParameters) soapFormatter.Deserialize(fileStream);

        // Close the file stream.
        fileStream.Close();

        return rsaParameter;

    }

要生成新的密钥,您可以使用RSACryptoServiceProvider.ExportParameters方法。


请参考以下内容:

RSAParameters结构


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接