protected void SignDetached(Stream signed, Stream unsigned, X509Certificate2 selectedCert) { BC::X509.X509Certificate bcSelectedCert = DotNetUtilities.FromX509Certificate(selectedCert); #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Information, 0, "Signing the message in name of {0}", selectedCert.Subject); #else logger.LogInformation("Signing the message in name of {0}", selectedCert.Subject); #endif BC.Crypto.ISignatureFactory sigFactory; try { SignatureAlgorithm signAlgo = EteeActiveConfig.Seal.NativeSignatureAlgorithm; BC::Crypto.AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(selectedCert.PrivateKey); sigFactory = new Asn1SignatureFactory(signAlgo.Algorithm.FriendlyName, keyPair.Private); } catch (CryptographicException) { SignatureAlgorithm signAlgo = EteeActiveConfig.Seal.WindowsSignatureAlgorithm; sigFactory = new WinSignatureFactory(signAlgo.Algorithm, signAlgo.DigestAlgorithm, selectedCert.PrivateKey); } SignerInfoGenerator sigInfoGen = new SignerInfoGeneratorBuilder() .Build(sigFactory, bcSelectedCert); CmsSignedDataGenerator cmsSignedDataGen = new CmsSignedDataGenerator(); cmsSignedDataGen.AddSignerInfoGenerator(sigInfoGen); CmsSignedData detachedSignature = cmsSignedDataGen.Generate(new CmsProcessableProxy(unsigned), false); byte[] detachedSignatureBytes = detachedSignature.GetEncoded(); signed.Write(detachedSignatureBytes, 0, detachedSignatureBytes.Length); }
/* * /// <exception cref="System.IO.IOException"></exception> * public override Document ExtendDocument(Document document, Document originalDocument * , SignatureParameters parameters) * { * CAdESSignatureExtension extension = GetExtensionProfile(parameters); * if (extension != null) * { * return extension.ExtendSignatures(document, originalDocument, parameters); * } * else * { * //LOG.Info("No extension for " + parameters.SignatureFormat); * } * return document; * } */ private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ISignatureFactory factory, SignatureParameters parameters, CAdESProfileBES cadesProfile, bool includeUnsignedAttributes, CmsSignedData originalSignedData ) { var signedAttrGen = new DefaultSignedAttributeTableGenerator( new AttributeTable(cadesProfile.GetSignedAttributes(parameters))); SimpleAttributeTableGenerator unsignedAttrGen = null; if (includeUnsignedAttributes) { var attributes = cadesProfile.GetUnsignedAttributes(parameters); if (attributes.Count != 0) { unsignedAttrGen = new SimpleAttributeTableGenerator(new AttributeTable(attributes)); } } SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(); sigInfoGeneratorBuilder.WithSignedAttributeGenerator(signedAttrGen); if (unsignedAttrGen != null) { sigInfoGeneratorBuilder.WithUnsignedAttributeGenerator(unsignedAttrGen); } CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSignerInfoGenerator(sigInfoGeneratorBuilder.Build(factory, parameters.SigningCertificate)); if (originalSignedData != null) { generator.AddSigners(originalSignedData.GetSignerInfos()); } var certs = new List <X509Certificate>(); certs.Add(parameters.SigningCertificate); if (parameters.CertificateChain != null) { foreach (X509Certificate cert in parameters.CertificateChain) { if (!cert.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN)) { certs.Add(cert); } } } IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); generator.AddCertificates(certStore); if (originalSignedData != null) { generator.AddCertificates(originalSignedData.GetCertificates("Collection")); } return(generator); }
private static string SignEnvelop(string signCert, string password, string envelopCert, string orgData) { var pkcs12StoreBuilder = new Pkcs12StoreBuilder(); var pkcs12Store = pkcs12StoreBuilder.Build(); pkcs12Store.Load(new MemoryStream(Convert.FromBase64String(signCert)), password.ToCharArray()); var aliases = pkcs12Store.Aliases; var enumerator = aliases.GetEnumerator(); enumerator.MoveNext(); var alias = enumerator.Current.ToString(); var privKey = pkcs12Store.GetKey(alias); var x509Cert = pkcs12Store.GetCertificate(alias).Certificate; var sha1Signer = SignerUtilities.GetSigner("SHA1withRSA"); sha1Signer.Init(true, privKey.Key); var gen = new CmsSignedDataGenerator(); gen.AddSignerInfoGenerator(new SignerInfoGeneratorBuilder().Build(new Asn1SignatureFactory("SHA1withRSA", privKey.Key), x509Cert)); gen.AddCertificates(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(new ArrayList { x509Cert }))); var sigData = gen.Generate(new CmsProcessableByteArray(Encoding.UTF8.GetBytes(orgData)), true); var signData = sigData.GetEncoded(); var certificate = DotNetUtilities.FromX509Certificate(new X509Certificate2(Convert.FromBase64String(envelopCert))); var rst = Convert.ToBase64String(EncryptEnvelop(certificate, signData)); return(rst); }
private string DigitalSign(string location, string id, string password, byte[] data) { foreach (var certificatePair in GetCertificates(location)) { var certId = GetCertificateId(certificatePair.Key); if (certId == id) { var rsa = CertificateManager.DecryptPrivateKey(certificatePair.Value, password); if (rsa == null) { return(null); } var privateKey = DotNetUtilities.GetKeyPair(rsa).Private; var signatureFactory = new Asn1SignatureFactory("SHA1WITHRSA", privateKey); var signerInfoGenerator = new SignerInfoGeneratorBuilder().Build(signatureFactory, DotNetUtilities.FromX509Certificate(certificatePair.Key)); var generator = new CmsSignedDataGenerator(); generator.AddSignerInfoGenerator(signerInfoGenerator); var signedData = generator.Generate(new CmsProcessableByteArray(data), true); return(Uri.EscapeDataString(Convert.ToBase64String(signedData.GetEncoded()))); } } return(null); }
byte[] CreateKeyVaultSignature(X509Certificate2 publicCert, SignatureManifest signatureManifest) { var chain = new X509Chain(); chain.Build(publicCert); // Get the chain as bc certs var additionals = chain.ChainElements.Cast <X509ChainElement>() .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate)) .ToList(); chain.Dispose(); var bcCer = DotNetUtilities.FromX509Certificate(publicCert); var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals)); var generator = new CmsSignedDataGenerator(); var builder = new SignerInfoGeneratorBuilder(); var b = builder.Build(new RsaSignatureFactory("SHA256WITHRSA", provider), bcCer); generator.AddSignerInfoGenerator(b); generator.AddCertificates(store); var msg = new CmsProcessableByteArray(signatureManifest.GetBytes()); var data = generator.Generate(msg, true); var encoded = data.GetEncoded(); return(encoded); }
PrimarySignature CreateKeyVaultPrimarySignature(SignPackageRequest request, SignatureContent signatureContent, SignatureType signatureType) { // Get the chain var getter = typeof(SignPackageRequest).GetProperty("Chain", BindingFlags.Instance | BindingFlags.NonPublic) .GetGetMethod(true); var certs = (IReadOnlyList <X509Certificate2>)getter.Invoke(request, null); var attribs = SigningUtility.CreateSignedAttributes(request, certs); // Convert .NET crypto attributes to Bouncy Castle var attribTable = new AttributeTable(new Asn1EncodableVector(attribs.Cast <CryptographicAttributeObject>() .Select(ToBcAttribute) .ToArray())); // SignerInfo generator setup var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder() .WithSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(attribTable)); // Subject Key Identifier (SKI) is smaller and less prone to accidental matching than issuer and serial // number. However, to ensure cross-platform verification, SKI should only be used if the certificate // has the SKI extension attribute. // Try to look for the value var bcCer = DotNetUtilities.FromX509Certificate(request.Certificate); var ext = bcCer.GetExtensionValue(new DerObjectIdentifier(Oids.SubjectKeyIdentifier)); SignerInfoGenerator signerInfoGenerator; if (ext != null) { var ski = new SubjectKeyIdentifierStructure(ext); signerInfoGenerator = signerInfoGeneratorBuilder.Build(new RsaSignatureFactory(HashAlgorithmToBouncyCastle(request.SignatureHashAlgorithm), provider), ski.GetKeyIdentifier()); } else { signerInfoGenerator = signerInfoGeneratorBuilder.Build(new RsaSignatureFactory(HashAlgorithmToBouncyCastle(request.SignatureHashAlgorithm), provider), bcCer); } var generator = new CmsSignedDataGenerator(); generator.AddSignerInfoGenerator(signerInfoGenerator); // Get the chain as bc certs generator.AddCertificates(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs.Select(DotNetUtilities.FromX509Certificate). ToList()))); var msg = new CmsProcessableByteArray(signatureContent.GetBytes()); var data = generator.Generate(msg, true); var encoded = data.ContentInfo.GetDerEncoded(); return(PrimarySignature.Load(encoded)); }
public void SignedCmsRoundTripWithBouncyCastleLocalCertificate() { var content = "This is some content"; // Get cert var netcert = GetLocalSignerCert(); var chain = new X509Chain(); chain.Build(netcert); // Get the chain without the root CA var additionals = chain.ChainElements.Cast <X509ChainElement>() .Where(ce => ce.Certificate.Issuer != ce.Certificate.SubjectName.Name) .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate)) .ToList(); chain.Dispose(); var bcCer = DotNetUtilities.FromX509Certificate(netcert); var bcKey = DotNetUtilities.GetRsaKeyPair(netcert.GetRSAPrivateKey()); var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals)); var generator = new CmsSignedDataGenerator(); var builder = new SignerInfoGeneratorBuilder(); var b = builder.Build(new Asn1SignatureFactory("SHA256WITHRSA", bcKey.Private), bcCer); generator.AddSignerInfoGenerator(b); // generator.AddSigner(bcKey.Private, bcCer, CmsSignedDataGenerator.DigestSha256); generator.AddCertificates(store); var msg = new CmsProcessableByteArray(Encoding.UTF8.GetBytes(content)); var data = generator.Generate(msg, true); var encoded = data.GetEncoded(); var signedCms = new SignedCms(); signedCms.Decode(encoded); signedCms.CheckSignature(true); // don't validate the certiciate itself here var cContent = signedCms.ContentInfo.Content; var str = Encoding.UTF8.GetString(cContent); Assert.Equal(content, str); }
public void AssinarCriptografar(EnvioRemessaCobrancaBradescoJson model) { try { var utilClass = new MetodosUteis(); var encoding = new UTF8Encoding(); var generator = new CmsSignedDataGenerator(); var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(); var certList = new ArrayList(); var criticas = utilClass.Criticas(model); if (criticas.Any()) { return; } var data = utilClass.ConverterParaJsonAspasSimples(model); var privateCert = this.RetornaCertificado(); //convertendo certificado para objeto que o bouncycastle conhece var bouncyCastleKey = DotNetUtilities.GetKeyPair(privateCert.PrivateKey).Private; var x5091 = new X509Certificate(privateCert.RawData); var x509CertBouncyCastle = DotNetUtilities.FromX509Certificate(x5091); generator.AddSignerInfoGenerator(signerInfoGeneratorBuilder.Build(new Asn1SignatureFactory("SHA256WithRSA", bouncyCastleKey), x509CertBouncyCastle)); //criando certstore que o bouncycastle conhece certList.Add(x509CertBouncyCastle); var store509BouncyCastle = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList)); generator.AddCertificates(store509BouncyCastle); var messageBytes = encoding.GetBytes(data); var cmsdata = new CmsProcessableByteArray(messageBytes); //assina var signeddata = generator.Generate(cmsdata, true); var mensagemFinal = signeddata.GetEncoded(); //converte para base64 que eh o formato que o serviço espera var mensagemConvertidaparaBase64 = Convert.ToBase64String(mensagemFinal); //chama serviço convertendo a string na base64 em bytes EnviaParaWebService(ParametrosUteis.RetornaUrlEnvio(), encoding.GetBytes(mensagemConvertidaparaBase64)); } catch (Exception ex) { throw ex; } }
public async void SignedCmsRoundTripWithKeyVault() { using (var materialized = await KeyVaultConfigurationDiscoverer.Materialize(certificateConfiguration)) { var content = "This is some content"; var publicCert = materialized.PublicCertificate; // Get cert var chain = new X509Chain(); chain.Build(publicCert); // Get the chain without the root CA var additionals = chain.ChainElements.Cast <X509ChainElement>() .Where(ce => ce.Certificate.Issuer != ce.Certificate.SubjectName.Name) .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate)) .ToList(); chain.Dispose(); var bcCer = DotNetUtilities.FromX509Certificate(publicCert); var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals)); var generator = new CmsSignedDataGenerator(); var builder = new SignerInfoGeneratorBuilder(); var b = builder.Build(new RsaSignatureFactory("SHA256WITHRSA", materialized.ToRSA()), bcCer); generator.AddSignerInfoGenerator(b); generator.AddCertificates(store); var msg = new CmsProcessableByteArray(Encoding.UTF8.GetBytes(content)); var data = generator.Generate(msg, true); var encoded = data.GetEncoded(); var signedCms = new SignedCms(); signedCms.Decode(encoded); signedCms.CheckSignature(true); // don't validate the certiciate itself here var cContent = signedCms.ContentInfo.Content; var str = Encoding.UTF8.GetString(cContent); Assert.Equal(content, str); } }
public SignatureFileContainer CreateCadesSignatureFile(ManifestContainer manifestContainer) { var signedDataGenerator = new CmsSignedDataGenerator(); signedDataGenerator.AddSigner( this.certificateHolder.GetPrivateKey(), this.certificateHolder.GetPublicCertificate(), CmsSignedDataGenerator.DigestSha256); signedDataGenerator.AddSignerInfoGenerator(CreateSignerInfoGenerator()); signedDataGenerator.AddCertificates(CreateX509Store()); var signedData = signedDataGenerator.Generate(new CmsProcessableByteArray(manifestContainer.Data.ToArray())); return(new SignatureFileContainer(manifestContainer.SignatureFileRef, signedData.GetEncoded())); }
private static void SavePkcs7Data(X509Certificate bcCertificate, Pkcs10CertificationRequest request, AsymmetricKeyParameter privateKey) { var requestBytes = request.GetEncoded(); var typedData = new CmsProcessableByteArray(requestBytes); var gen = new CmsSignedDataGenerator(); var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(); var factory = new Asn1SignatureFactory(SingingAlgorithm, privateKey); gen.AddSignerInfoGenerator(signerInfoGeneratorBuilder.Build(factory, bcCertificate)); gen.AddCertificates(MakeCertStore(bcCertificate)); var signed = gen.Generate(typedData, true); var signedBytes = signed.GetEncoded(); var cmsBase64 = Convert.ToBase64String(signedBytes); /* * you can check cert data here - https://lapo.it/asn1js * just copy+paste cmsBase64 string */ var cmsData = new StringBuilder(); cmsData.Append("-----BEGIN CMS-----"); cmsData.Append("\\n"); var certLength = cmsBase64.Length; for (var i = 0; i < certLength; i += 64) { var substr = certLength - i >= 64 ? cmsBase64.Substring(i, 64) : cmsBase64.Substring(i); cmsData.Append(substr); cmsData.Append("\\n"); } cmsData.Append("-----END CMS-----"); cmsData.Append("\\n"); var cmsString = cmsData.ToString(); //add to http request in bank for approving you certificate //after you will need copy bank certificate what approved you certificate from API File.WriteAllText(@"certificate.cms", cmsString); }
private byte[] Authenticode(byte[] bRequest, DateTime signTime) { string requestString = ""; for (int i = 0; i < bRequest.Length; i++) { if (bRequest[i] >= 32) { requestString += (char)bRequest[i]; } } bRequest = Convert.FromBase64String(requestString); Asn1InputStream asn1InputStream = new Asn1InputStream(bRequest); Asn1Sequence instance = Asn1Sequence.GetInstance(asn1InputStream.ReadObject()); Asn1Sequence instance2 = Asn1Sequence.GetInstance(instance[1]); Asn1TaggedObject instance3 = Asn1TaggedObject.GetInstance(instance2[1]); Asn1OctetString instance4 = Asn1OctetString.GetInstance(instance3.GetObject()); byte[] octets = instance4.GetOctets(); asn1InputStream.Close(); Asn1EncodableVector signedAttributes = new Asn1EncodableVector(); signedAttributes.Add(new Attribute(CmsAttributes.ContentType, new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1")))); signedAttributes.Add(new Attribute(CmsAttributes.SigningTime, new DerSet(new DerUtcTime(signTime)))); AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); signedAttributesTable.ToAsn1EncodableVector(); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable); SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(); signerInfoBuilder.WithSignedAttributeGenerator(signedAttributeGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory(hashAlg + "WithRSA", priKey); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSignerInfoGenerator(signerInfoBuilder.Build(signatureFactory, x509Cert)); generator.AddCertificates(x509Store); CmsSignedData cmsSignedData = generator.Generate(new CmsProcessableByteArray(octets), true); byte[] result = cmsSignedData.ContentInfo.GetEncoded("DER"); return(Encoding.ASCII.GetBytes(Convert.ToBase64String(result).ToArray())); }
public string Signer(string message) { if (_certificate == null) { throw new Exception("Certificado não localizado."); } if (_certificate.PrivateKey == null) { throw new Exception("chave privada não localizada no certificado."); } //convertendo certificado para objeto que o bouncycastle conhece var bouncyCastleKey = DotNetUtilities.GetKeyPair(_certificate.PrivateKey).Private; var x5091 = new X509Certificate(_certificate.RawData); var x509CertBouncyCastle = DotNetUtilities.FromX509Certificate(x5091); var generator = new CmsSignedDataGenerator(); var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(); generator.AddSignerInfoGenerator( signerInfoGeneratorBuilder.Build(new Asn1SignatureFactory("SHA256WithRSA", bouncyCastleKey), x509CertBouncyCastle)); //criando certstore que o bouncycastle conhece IList certList = new ArrayList(); certList.Add(x509CertBouncyCastle); var store509BouncyCastle = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList)); generator.AddCertificates(store509BouncyCastle); var encoding = new UTF8Encoding(); var messageBytes = encoding.GetBytes(message); var cmsdata = new CmsProcessableByteArray(messageBytes); //assina var signeddata = generator.Generate(cmsdata, true); var finalMessage = signeddata.GetEncoded(); //converte para base64 que eh o formato que o serviço espera return(Convert.ToBase64String(finalMessage)); }
public byte[] Sign(Stream data) { CmsProcessable msg = new CmsProcessableInputStream(data); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); SignerInfoGenerator signerInfoGenerator = new SignerInfoGeneratorBuilder() .WithSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator()) .Build(new Asn1SignatureFactory(algorithm, key), chain[0]); gen.AddSignerInfoGenerator(signerInfoGenerator); X509CollectionStoreParameters collectionStoreParameters = new X509CollectionStoreParameters(new List <X509Certificate>(chain)); IX509Store collectionStore = X509StoreFactory.Create("CERTIFICATE/COLLECTION", collectionStoreParameters); gen.AddCertificates(collectionStore); CmsSignedData sigData = gen.Generate(msg, false); return(sigData.GetEncoded()); }
private CmsSignedDataGenerator CreateCMSSignedDataGenerator(SignatureParameters parameters, CAdESProfileBES cadesProfile, bool includeUnsignedAttributes = true, CmsSignedData originalSignedData = null, byte[] signature = null) { CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); X509Certificate signerCertificate = parameters.SigningCertificate; CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator(new AttributeTable(cadesProfile.GetSignedAttributes(parameters) as System.Collections.IDictionary)); CmsAttributeTableGenerator unsignedAttrGen = new SimpleAttributeTableGenerator(includeUnsignedAttributes ? new AttributeTable(cadesProfile.GetUnsignedAttributes(parameters) as System.Collections.IDictionary) : null); var builder = new SignerInfoGeneratorBuilder().WithSignedAttributeGenerator(signedAttrGen).WithUnsignedAttributeGenerator(unsignedAttrGen); generator.AddSignerInfoGenerator(builder.Build(new ReadySignatureFactory(new PreComputedSigner(signature), parameters.DigestWithEncriptionOID), signerCertificate)); if (originalSignedData != null) { generator.AddSigners(originalSignedData.GetSignerInfos()); } var certs = new List <X509Certificate> { parameters.SigningCertificate }; if (parameters.CertificateChain != null) { foreach (X509Certificate c in parameters.CertificateChain) { if (!c.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN)) { certs.Add(c); } } } IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); generator.AddCertificates(certStore); if (originalSignedData != null) { generator.AddCertificates(originalSignedData.GetCertificates("Collection")); } return(generator); }
protected void SignDetached(Stream signed, Stream unsigned, BC::Crypto.AsymmetricCipherKeyPair bcKeyPair, byte[] keyId) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Information, 0, "Signing the message in name of {0}", Convert.ToBase64String(keyId)); #else logger.LogInformation("Signing the message in name of {0}", Convert.ToBase64String(keyId)); #endif SignatureAlgorithm signAlgo = EteeActiveConfig.Seal.NativeSignatureAlgorithm; var sigFactory = new Asn1SignatureFactory(signAlgo.Algorithm.FriendlyName, bcKeyPair.Private); SignerInfoGenerator sigInfoGen = new SignerInfoGeneratorBuilder() .Build(sigFactory, keyId); CmsSignedDataGenerator cmsSignedDataGen = new CmsSignedDataGenerator(); cmsSignedDataGen.AddSignerInfoGenerator(sigInfoGen); CmsSignedData detachedSignature = cmsSignedDataGen.Generate(new CmsProcessableProxy(unsigned), false); byte[] detachedSignatureBytes = detachedSignature.GetEncoded(); signed.Write(detachedSignatureBytes, 0, detachedSignatureBytes.Length); }
// https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSSignedDataGenerator.html private void SignInternal( System.Security.Cryptography.X509Certificates.X509Certificate2 certificate , byte[] data) { // https://stackoverflow.com/questions/3240222/get-private-key-from-bouncycastle-x509-certificate-c-sharp // Org.BouncyCastle.X509.X509Certificate c = FromX509Certificate(certificate); //var algorithm = LumiSoft.Net.X509.DigestAlgorithms.GetDigest(c.SigAlgOid); //var signature = new LumiSoft.Net.X509.X509Certificate2Signature(this.m_certificate, algorithm); //signature.Sign(data); CmsProcessable msg = new Org.BouncyCastle.Cms.CmsProcessableByteArray(data); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); Org.BouncyCastle.Security.SecureRandom random = new Org.BouncyCastle.Security.SecureRandom(); Org.BouncyCastle.X509.X509Certificate c = FromX509Certificate(certificate); Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair issuerKeys = GetKeyPair(certificate.PrivateKey); string signatureAlgo = certificate.PrivateKey is RSA ? "SHA1withRSA" : certificate.PrivateKey is DSA ? "SHA1withDSA" : null; // var sha1Signer = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA1withRSA"); // https://stackoverflow.com/questions/3240222/get-private-key-from-bouncycastle-x509-certificate-c-sharp // https://stackoverflow.com/questions/36712679/bouncy-castles-x509v3certificategenerator-setsignaturealgorithm-marked-obsolete Org.BouncyCastle.Crypto.ISignatureFactory signatureFactory = new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory (signatureAlgo, issuerKeys.Private, random); // gen.AddCertificates(certs); gen.AddSignerInfoGenerator(new SignerInfoGeneratorBuilder() .Build(signatureFactory, c) ); this.m_signedData = gen.Generate(msg, false); }
/// <summary> /// 我也不晓得这个叫什么 /// </summary> /// <param name="orgData"></param> /// <returns></returns> public static string SignEnvelop(string orgData) { Pkcs12StoreBuilder pkcs12StoreBuilder = new Pkcs12StoreBuilder(); var pkcs12Store = pkcs12StoreBuilder.Build(); pkcs12Store.Load(File.OpenRead(PfxPath), pfxPwd.ToCharArray()); IEnumerable aliases = pkcs12Store.Aliases; var enumerator = aliases.GetEnumerator(); enumerator.MoveNext(); var alias = enumerator.Current.ToString(); var privKey = pkcs12Store.GetKey(alias); var x509Cert = pkcs12Store.GetCertificate(alias).Certificate; var sha1Signer = SignerUtilities.GetSigner("SHA1withRSA"); sha1Signer.Init(true, privKey.Key); var bs = Encoding.UTF8.GetBytes(orgData); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSignerInfoGenerator( new SignerInfoGeneratorBuilder().Build(new Asn1SignatureFactory("SHA1withRSA", privKey.Key), x509Cert)); IList certList = new ArrayList(); certList.Add(x509Cert); gen.AddCertificates(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList))); var msg = new CmsProcessableByteArray(bs); var sigData = gen.Generate(msg, true); var signData = sigData.GetEncoded(); var certificate = DotNetUtilities.FromX509Certificate(new SystemX509.X509Certificate(CertPath)); var rst = Convert.ToBase64String(EncryptEnvelop(certificate, signData)); return(rst); }
private static string Cms(string data) { var requestBytes = Encoding.UTF8.GetBytes(data); var typedData = new CmsProcessableByteArray(requestBytes); var gen = new CmsSignedDataGenerator(); var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(); var attrs = GetSigningParameters(); var parameters = new DefaultSignedAttributeTableGenerator(attrs); signerInfoGeneratorBuilder.WithSignedAttributeGenerator(parameters); var factory = new Asn1SignatureFactory(SingingAlgorithm, GetKey()); var bcCertificate = GetBankCertificate(); gen.AddSignerInfoGenerator(signerInfoGeneratorBuilder.Build(factory, bcCertificate)); gen.AddCertificates(MakeCertStore(bcCertificate)); var signed = gen.Generate(typedData, false); var signedBytes = signed.GetEncoded(); return(Convert.ToBase64String(signedBytes)); }
public TimeStampToken Generate( TimeStampRequest request, BigInteger serialNumber, DateTime genTime, X509Extensions additionalExtensions) { DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid); AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance); MessageImprint messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest()); Accuracy accuracy = null; if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) { DerInteger seconds = null; if (accuracySeconds > 0) { seconds = new DerInteger(accuracySeconds); } DerInteger millis = null; if (accuracyMillis > 0) { millis = new DerInteger(accuracyMillis); } DerInteger micros = null; if (accuracyMicros > 0) { micros = new DerInteger(accuracyMicros); } accuracy = new Accuracy(seconds, millis, micros); } DerBoolean derOrdering = null; if (ordering) { derOrdering = DerBoolean.GetInstance(ordering); } DerInteger nonce = null; if (request.Nonce != null) { nonce = new DerInteger(request.Nonce); } DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID); if (request.ReqPolicy != null) { tsaPolicy = new DerObjectIdentifier(request.ReqPolicy); } X509Extensions respExtensions = request.Extensions; if (additionalExtensions != null) { X509ExtensionsGenerator extGen = new X509ExtensionsGenerator(); if (respExtensions != null) { foreach (object oid in respExtensions.ExtensionOids) { DerObjectIdentifier id = DerObjectIdentifier.GetInstance(oid); extGen.AddExtension(id, respExtensions.GetExtension(DerObjectIdentifier.GetInstance(id))); } } foreach (object oid in additionalExtensions.ExtensionOids) { DerObjectIdentifier id = DerObjectIdentifier.GetInstance(oid); extGen.AddExtension(id, additionalExtensions.GetExtension(DerObjectIdentifier.GetInstance(id))); } respExtensions = extGen.Generate(); } DerGeneralizedTime generalizedTime; if (resolution != Resolution.R_SECONDS) { generalizedTime = new DerGeneralizedTime(createGeneralizedTime(genTime)); } else { generalizedTime = new DerGeneralizedTime(genTime); } TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint, new DerInteger(serialNumber), generalizedTime, accuracy, derOrdering, nonce, tsa, respExtensions); try { CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator(); byte[] derEncodedTstInfo = tstInfo.GetDerEncoded(); if (request.CertReq) { signedDataGenerator.AddCertificates(x509Certs); } signedDataGenerator.AddCrls(x509Crls); signedDataGenerator.AddSignerInfoGenerator(signerInfoGenerator); CmsSignedData signedData = signedDataGenerator.Generate( PkcsObjectIdentifiers.IdCTTstInfo.Id, new CmsProcessableByteArray(derEncodedTstInfo), true); return(new TimeStampToken(signedData)); } catch (CmsException cmsEx) { throw new TspException("Error generating time-stamp token", cmsEx); } catch (IOException e) { throw new TspException("Exception encoding info", e); } catch (X509StoreException e) { throw new TspException("Exception handling CertStore", e); } // catch (InvalidAlgorithmParameterException e) // { // throw new TspException("Exception handling CertStore CRLs", e); // } }
private void AssinarCriptografar(EnvioRemessaCobrancaBradescoJson model) { try { //exemplo validacao var validador = new ValidarModelo(); var criticas = validador.Criticas(model); if (criticas.Any()) { return; } var data = ConverterParaJsonAspasSimples(model); var encoding = new UTF8Encoding(); var messageBytes = encoding.GetBytes(data); var impressaDigitalCertificado = ConfigurationManager.AppSettings["ImpressaoDigitalCertificado"]; // certificado precisa ser instalado na máquina local e na pasta pessoal, diferente disso alterar linha abaixo var store = new X509Store(StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var privateCert = store.Certificates.Cast <X509Certificate2>().FirstOrDefault(cert => cert.Thumbprint == impressaDigitalCertificado && cert.HasPrivateKey); if (privateCert == null) { throw new Exception("Certificado não localizado."); } if (privateCert.PrivateKey == null) { throw new Exception("chave privada não localizada no certificado."); } //convertendo certificado para objeto que o bouncycastle conhece var bouncyCastleKey = DotNetUtilities.GetKeyPair(privateCert.PrivateKey).Private; var x5091 = new X509Certificate(privateCert.RawData); var x509CertBouncyCastle = DotNetUtilities.FromX509Certificate(x5091); var generator = new CmsSignedDataGenerator(); var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(); generator.AddSignerInfoGenerator( signerInfoGeneratorBuilder.Build(new Asn1SignatureFactory("SHA256WithRSA", bouncyCastleKey), x509CertBouncyCastle)); //criando certstore que o bouncycastle conhece IList certList = new ArrayList(); certList.Add(x509CertBouncyCastle); var store509BouncyCastle = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList)); generator.AddCertificates(store509BouncyCastle); var cmsdata = new CmsProcessableByteArray(messageBytes); //assina var signeddata = generator.Generate(cmsdata, true); var mensagemFinal = signeddata.GetEncoded(); //converte para base64 que eh o formato que o serviço espera var mensagemConvertidaparaBase64 = Convert.ToBase64String(mensagemFinal); //chama serviço convertendo a string na base64 em bytes CriarServicoWebEEnviar("url_servico_bradesco_consta_manual", encoding.GetBytes(mensagemConvertidaparaBase64)); } catch (Exception ex) { throw; } }