【问题标题】:how can sign a file with BouncyCastle dll in c#如何在 C# 中使用 BouncyCastle dll 签署文件
【发布时间】:2012-05-17 04:41:34
【问题描述】:

我从 BouncyCastle Crypto dll 开始,但没有找到足够的文档。 我需要一个示例,说明如何使用不同的算法对文件进行签名 像sha1 sha256 等,获取.p7m 文件。 有人可以帮助我吗? 提前谢谢了 皮尔卡洛

【问题讨论】:

  • BouncyCastle 是一个库,而不是一个应用程序。您需要在程序中使用它。您尝试使用什么语言,Java 或 C#。您找到了哪些文档,哪些明确让您感到困惑?
  • 是的,我知道我正在使用 c# 和 Visual Studio 进行编程
  • 我需要具体的例子,因为我从不使用密码学,实际上我需要使用证书签署文件以使用 sha256 算法检索 .p7m,然后从经过认证的时间服务器为其添加时间戳来执行.m7m 文件
  • 关于文档我只发现了 bouncyCastle 网站上的包内的内容,但我不太了解,因为它是零散的,没有描述完整的工作流程

标签: bouncycastle


【解决方案1】:

我为你整理了这个小例子:

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;

namespace ConsoleApplicationSignWithBouncyCastle
{
    class Program
    {

        [STAThread]
        static void Main(string[] args)
        {

            try
            {
                // First load a Certificate, filename/path and certificate password
                Cert = ReadCertFromFile("./test.pfx", "test");

                //  Select a binary file
                var dialog = new OpenFileDialog
                                 {
                                     Filter = "All files (*.*)|*.*",
                                     InitialDirectory = "./",
                                     Title = "Select a text file"
                                 };
                var filename = (dialog.ShowDialog() == DialogResult.OK) ? dialog.FileName : null;

                // Get the file
                var f = new FileStream(filename, System.IO.FileMode.Open);

                // Reading through this code stub to be sure I get it all :-)  [ Different subject entirely ]
                var fileContent = ReadFully(f);

                // Create the generator
                var dataGenerator = new CmsEnvelopedDataStreamGenerator();

                // Add receiver
                // Cert is the user's X.509 Certificate set bellow
                dataGenerator.AddKeyTransRecipient(Cert);

                // Make the output stream
                var outStream = new FileStream(filename + ".p7m", FileMode.Create);

                // Sign the stream
                var cryptoStream = dataGenerator.Open(outStream, CmsEnvelopedGenerator.Aes128Cbc);

                // Store in our binary stream writer and write the signed content
                var binWriter = new BinaryWriter(cryptoStream);
                binWriter.Write(fileContent);
            }
            catch (Exception ex)
            {
                Console.WriteLine("So, you wanna make an exception huh! : " + ex.ToString());
                Console.ReadKey();
            }
        }

        public static byte[] ReadFully(Stream stream)
        {
            stream.Seek(0, 0);
            var buffer = new byte[32768];
            using (var ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }

        public static Org.BouncyCastle.X509.X509Certificate Cert { get; set; }

        // This reads a certificate from a file.
        // Thanks to: http://blog.softwarecodehelp.com/2009/06/23/CodeForRetrievePublicKeyFromCertificateAndEncryptUsingCertificatePublicKeyForBothJavaC.aspx
        public static X509Certificate ReadCertFromFile(string strCertificatePath, string strCertificatePassword)
        {
            try
            {
                // Create file stream object to read certificate
                var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read);

                // Read certificate using BouncyCastle component
                var inputKeyStore = new Pkcs12Store();
                inputKeyStore.Load(keyStream, strCertificatePassword.ToCharArray());

                //Close File stream
                keyStream.Close();

                var keyAlias = inputKeyStore.Aliases.Cast<string>().FirstOrDefault(n => inputKeyStore.IsKeyEntry(n));

                // Read Key from Alieases  
                if (keyAlias == null)
                    throw new NotImplementedException("Alias");

                //Read certificate into 509 format
                return (X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate;
            }
            catch (Exception ex)
            {
                Console.WriteLine("So, you wanna make an exception huh! : " + ex.ToString());
            Console.ReadKey();
            return null;
        }
    }
} }

希望这会有所帮助。

我也发了on my blog

【讨论】:

  • 我尝试了您的示例,但不起作用我的证书在智能卡内,当我在 MyStore 中将证书提供给他时,不要向 frp CSP 询问证书,结果 file.p7m 是一个无效文件,即不包含原始文件我需要嵌入签名
猜你喜欢
  • 1970-01-01
  • 2015-08-04
  • 2021-09-19
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多