开始使用 BouncyCastle crypto dll c#

发布于 2024-09-27 17:57:44 字数 212 浏览 0 评论 0原文

我是密码学初学者,

我想将 BouncyCastle .dll 用于 c#,但我找不到文档和示例。

特别是,我需要使用 pkcs#7(.p7m 结果)对文件进行签名,并向其中添加符合 RFC 3161 标准的来自受信任服务器的时间戳(.m7m 结果)。

有人可以建议我在哪里可以找到示例和文档来执行此操作?

预先致谢

最诚挚的问候

I'm starter with cryptography

I woul like to use BouncyCastle .dll for c# but I cannot found documentation and examples.

In particulary I need to use to sign files with pkcs#7 (.p7m results) and add to them RFC 3161–compliant, time stamps from trusted server (.m7m results).

somebody can suggest where I can found examples and documentation to do this ?

Thanking in advance

Best regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮惑 2024-10-04 17:57:44

我为 #SO 上的另一个问题整理了这个小例子,但它也适用于您:

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;
        }
    }
} }

希望这会有所帮助。

我还在我的网站上发布了博客

I put together this little example for another question here on #SO, but it applies to you as well:

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;
        }
    }
} }

Hope this helps.

I also posted it on my blog.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文