我需要使用RSA 1.5算法加密一个字符串。我已经拥有了私钥,但是我无法弄清楚如何将此密钥添加到类中。似乎该密钥必须是RSAParameter结构类型的。然而,这需要一组值,例如模数、指数、P、Q等,但我只有私钥。有人能帮忙吗?
我需要使用RSA 1.5算法加密一个字符串。我已经拥有了私钥,但是我无法弄清楚如何将此密钥添加到类中。似乎该密钥必须是RSAParameter结构类型的。然而,这需要一组值,例如模数、指数、P、Q等,但我只有私钥。有人能帮忙吗?
你应该了解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);
}
}
}
我猜这就是你要找的内容:
// 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方法。
请参考以下内容: