这是等效的OpenSSL commad这个C#代码签名

时间:2017-07-28 11:20:27

标签: c# openssl digital-signature pkcs#7

我有以下代码来签署文件:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Pkcs;
using System.Text;
using System.Threading.Tasks;
using Disig.TimeStampClient;
using System.Xml.Linq;

namespace ClientTest
{
    class Program
    {
        static void Main(string[] args)
        {

            var certificate = GetCertificate("mycert.pfx", "password");
            var data = File.ReadAllBytes("data.bin");
            var signature = ComputeSignature(data, certificate);
            SavePemSignature(signature, "file-signature.pem");
        }

        static void SavePemSignature(byte[] signature, string filePath)
        {
            var base64 = Convert.ToBase64String(signature);
            using (var writer = new StreamWriter(filePath, false, Encoding.Default))
            {

                writer.WriteLine("-----BEGIN CMS-----");
                var pos = 0;
                while (pos < base64.Length)
                {
                    var len = Math.Min(64, base64.Length - pos);
                    var line = base64.Substring(pos, len);
                    writer.WriteLine(line);
                    pos += len;
                }
                writer.WriteLine("-----END CMS-----");
            }
        }



        static byte[] ComputeSignature(byte[] data, X509Certificate2 certificate)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            ContentInfo content = new ContentInfo(data);
            SignedCms signedCms = new SignedCms(content, true);
            CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, certificate);
            signer.DigestAlgorithm = System.Security.Cryptography.Oid.FromFriendlyName("SHA256", System.Security.Cryptography.OidGroup.HashAlgorithm);
            signedCms.ComputeSignature(signer);
            return signedCms.Encode();
        }

        static X509Certificate2 GetCertificate(string filePath, string password)
        {
            X509Certificate2Collection collection = new X509Certificate2Collection();
            collection.Import(filePath, password, X509KeyStorageFlags.PersistKeySet);
            var cert = collection.Cast<X509Certificate2>()
                .FirstOrDefault(x => x.PrivateKey != null && x.Extensions.OfType<X509KeyUsageExtension>().FirstOrDefault(c => (c.KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature) != null);
            return cert;
        }
    }
}

哪个是等效的openssl命令?

我尝试了以下内容,但我没有运气,pem文件不同:

openssl cms -in data.bin -sign -signer mycert.pem -md SHA256 -binary -noattr -outform pem -out file-signature.pem

0 个答案:

没有答案