2011-05-17 178 views
10

我需要使用RSA 1.5算法加密字符串。我已经提供了一个私钥。但是,我不能为了我的生活找出如何将这个关键词添加到课程中。 RSAParameter stuct类似的关键需求是。然而,这需要一系列我没有给出的值,例如Modulus,Exponent,P,Q等等。我拥有的只是私钥。谁能帮忙?.NET私钥Rsa加密

+0

什么你有明显的关键,你可能不希望为它供给逐字,但你可以形容它多一些? – Jodrell 2011-05-17 11:19:23

+0

发布您尝试过的内容。我怀疑你根本不明白RSA的工作原理如何。我不知道你使用了哪些课程,所以我不能提供建议。阅读此:http://stackoverflow.com/questions/1181421/is-possible-to-encrypt-with-private-key-using-net-rsacryptoserviceprovider – 2011-05-17 11:25:04

+1

我提供的密钥看起来像----- BEGIN RSA PRIVATE KEY ----- MIIadfdafCXdfawIBAAKBgQCIgynd6pvlCF = ----- END RSA PRIVATE KEY ----- ----- BEGIN PUBLIC KEY ----- jaz + wadfadIDAQAB ----- END PUBLIC KEY ----- 这是我拥有的全部.. – 2011-05-17 11:29:03

回答

24

你应该知道的Bouncycastle C# library的。特别有两个非常有用的类: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); 
     } 
    } 
} 
+0

谢谢!这正是我需要的。 – 2011-05-18 01:42:38

+0

我一直在寻找很多地方正是这个......谢谢! – MattyP 2012-08-16 16:49:06

+0

我需要用Java完成这件事。当我使用pr.readObject()时,它将返回PEMKeyPair并在将其转换为AsymmetricCipherKeyPair时引发异常。我无法弄清楚为什么我的生活。请帮忙! – c0d3Junk13 2013-04-04 22:12:40

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 Structure