【问题标题】:.NET Private Key Rsa Encryption.NET 私​​钥 Rsa 加密
【发布时间】:2011-05-17 11:09:24
【问题描述】:

我需要使用 RSA 1.5 算法加密字符串。我得到了一个私钥。但是,我一生都无法弄清楚如何将此密钥添加到课程中。似乎密钥需要是 RSAParameter stuct 类型。然而,这需要一组我没有给出的值,例如模数、指数、P、Q 等。我所拥有的只是私钥。有人可以帮忙吗?

【问题讨论】:

  • 显然你有什么钥匙,你可能不想逐字提供它,但你能再描述一下吗?
  • 发布您尝试过的内容。老实说,我怀疑您根本不了解 RSA 的工作原理。我不知道你到底在使用什么课程,所以我无法提供建议。阅读:stackoverflow.com/questions/1181421/…
  • 我提供的密钥看起来像 -----BEGIN RSA PRIVATE KEY-----MIIadfdafCXdfawIBAAKBgQCIgynd6pvlCF= -----END RSA PRIVATE KEY------ -BEGIN PUBLIC KEY-----jaz+wadfadIDAQAB -----END PUBLIC KEY----- 这就是我所拥有的..

标签: c# .net cryptography rsa


【解决方案1】:

您应该知道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);
        }
    }
}

【讨论】:

  • 谢谢!!这正是我所需要的。
  • 我已经在很多地方寻找这个...谢谢!
  • 我需要在 Java 中完成这件事。当我使用 pr.readObject() 时,它返回 PEMKeyPair 并在我将其转换为 AsymmetricCipherKeyPair 时抛出异常。我无法弄清楚为什么我的生活。请帮忙!
  • 为我引发了 InvalidCastException。
  • @mikerobi:您确定您的密钥文件包含私钥吗?
【解决方案2】:

我猜这就是你要找的东西:

    // 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 2015-12-25
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2013-06-08
    相关资源
    最近更新 更多