.NET私钥Rsa加密

Ste*_*iss 11 .net c# cryptography rsa

我需要使用RSA 1.5算法加密字符串.我已获得私钥.但是,我不能为我的生活弄清楚如何将这个键添加到班级.似乎关键需要是RSAParameter stuct类型.然而,这需要一组我没有给出的值,如模数,指数,P,Q等.我所拥有的只是私钥.有人可以帮忙吗?

Jam*_*olk 26

你应该知道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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Akr*_*hda 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;

    }
Run Code Online (Sandbox Code Playgroud)

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


请参阅以下内容:

RSAParameters结构