【问题标题】:Need to sign a string with RSASSA-PKCS1-v1_5 signature in c#需要在 c# 中使用 RSASSA-PKCS1-v1_5 签名对字符串进行签名
【发布时间】:2015-07-22 11:23:41
【问题描述】:

我有一个带有消息和私钥的字符串。我需要编写一些 C# 代码,可以使用 RSASSA-PKCS1-v1_5 签名对该字符串进行签名。

您对我应该从哪里着手完成这项工作有任何提示或建议吗? .NET 或可用库中是否有现有的 API 可以执行此操作?

【问题讨论】:

  • 稍微改写问题。

标签: c# signing


【解决方案1】:

这是一个如何做的例子,你可以在你的代码中进行必要的修改来实现它(例子来自MSDN Site:

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

class RSASample
{
   const string PubKeyFile = @"c:\encrypt\fileWithKey.pem";
   const string keyName = "Key01";
   CspParameters cspp = new CspParameters();
   RSAParameters RSAKeyInfo = new RSAParameters();

   Org.BouncyCastle.Utilities.IO.Pem.PemObject po = null;
   using (StreamReader sr = new StreamReader(PubKeyFile))
   {
        Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(reader);
        po = pr.ReadPemObject();
   }

   RSAKeyInfo.Modulus = po.Content;
   cspp.KeyContainerName = keyName;
   try
   {
        //Create a new instance of RSACryptoServiceProvider. 
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp))
        {
             rsa.PersistKeyInCsp = true;
             rsa.ImportParameters(RSAKeyInfo);
             //The hash to sign. 
             byte[] hash;
             using (SHA256 sha256 = SHA256.Create())
             {
                  byte[] data = new byte[] { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };
                  hash = sha256.ComputeHash(data);
             }


             //Create an RSASignatureFormatter object and pass it the  
             //RSACryptoServiceProvider to transfer the key information.
             RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);

             //Set the hash algorithm to SHA256.
             RSAFormatter.SetHashAlgorithm("SHA256");

             //Create a signature for HashValue and return it. 
             byte[] SignedHash = RSAFormatter.CreateSignature(hash);
             }
    }
    catch (CryptographicException e)
    {
         Console.WriteLine(e.Message);
    }
}

【讨论】:

  • 谢谢,但是我的私钥去哪儿了
  • pem 文件中的私钥
  • 这段代码在 Ruby 中完成了这项工作,但我需要在 c# 中完成。 key = OpenSSL::PKey::RSA.new(pemstring) key.sign(OpenSSL::Digest.new('sha256'), body).unpack('H*').first
  • 谢谢,我今天晚些时候试试
  • 但是你没有加载 PubKeyFile
猜你喜欢
  • 2017-05-13
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多