private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime?requestTimestamp = null)
        {
            var    signCertAlias = signCertificate.Aliases.Cast <string>().First(signCertificate.IsKeyEntry);
            var    signCertEntry = signCertificate.GetCertificate(signCertAlias);
            var    signCert      = signCertEntry.Certificate;
            var    signPkEntry   = signCertificate.GetKey(signCertAlias);
            var    signPk        = signPkEntry.Key;
            string digestName;

            if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id)
            {
                digestName = "SHA1";
            }
            else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id)
            {
                digestName = "SHA256";
            }
            else
            {
                throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}");
            }

            var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id;
            var digest    = DigestUtilities.CalculateDigest(digestName, data);

            var signedAttrs = new Dictionary <object, object>()
            {
                { CmsAttributeTableParameter.Digest, digest }
            };

            if (requestTimestamp.HasValue)
            {
                var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime())));
                signedAttrs.Add(signTimestamp.AttrType, signTimestamp);
            }

            var signedAttrGen   = new DefaultSignedAttributeTableGenerator();
            var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs);

            var generator = new CmsSignedDataGenerator();

            generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null);

            var signedData = generator.Generate(new CmsProcessableByteArray(data), true);

            return(signedData.GetEncoded());
        }
예제 #2
0
        public static Asn1DigestFactory Get(String mechanism)
        {
            DerObjectIdentifier oid = DigestUtilities.GetObjectIdentifier(mechanism);

            return(new Asn1DigestFactory(DigestUtilities.GetDigest(oid), oid));
        }