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); }
private void SignManigestFile(PassGeneratorRequest request) { X509Certificate2 card = GetCertificate(request); if (card == null) { throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct."); } Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; X509Certificate2 appleCA = GetAppleCertificate(); Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA); ArrayList intermediateCerts = new ArrayList(); intermediateCerts.Add(appleCert); intermediateCerts.Add(cert); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1); generator.AddCertificates(st1); CmsProcessable content = new CmsProcessableByteArray(manifestFile); CmsSignedData signedData = generator.Generate(content, false); signatureFile = signedData.GetEncoded(); }
public static byte[] GenerateSignature(List <X509Certificate> certificateChain, AsymmetricKeyEntry privateKey, byte[] messageToSign, AttributeTable signedAttributesTable) { X509Certificate signingCertificate = certificateChain[certificateChain.Count - 1]; #if MAX_CMS_COMPATIBILITY // Optional: This is the order that codesign uses: List <X509Certificate> cmsChain = new List <X509Certificate>(); if (certificateChain.Count > 1) { cmsChain.AddRange(certificateChain.GetRange(0, certificateChain.Count - 1)); cmsChain.Reverse(); } cmsChain.Add(signingCertificate); certificateChain = cmsChain; #endif IX509Store certificateStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certificateChain)); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); #if MAX_CMS_COMPATIBILITY // Optional: BouncyCastle v1.8.3 has the option to use DER instead of BER to store the certificate chain generator.UseDerForCerts = true; #endif generator.AddSigner(privateKey.Key, signingCertificate, CmsSignedDataGenerator.DigestSha256, signedAttributesTable, null); generator.AddCertificates(certificateStore); CmsSignedData cmsSignature = generator.Generate(CmsSignedGenerator.Data, new CmsProcessableByteArray(messageToSign), false); return(cmsSignature.GetEncoded()); }
private void SignManigestFile(PassGeneratorRequest request, string manifestFileAndPath) { byte[] dataToSign = File.ReadAllBytes(manifestFileAndPath); X509Certificate2 card = GetCertificate(request); Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; X509Certificate2 appleCA = GetAppleCertificate(); Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA); ArrayList intermediateCerts = new ArrayList(); intermediateCerts.Add(appleCert); intermediateCerts.Add(cert); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1); generator.AddCertificates(st1); CmsProcessable content = new CmsProcessableByteArray(dataToSign); CmsSignedData signedData = generator.Generate(content, false); string outputDirectory = Path.GetDirectoryName(manifestFileAndPath); string signatureFileAndPath = Path.Combine(outputDirectory, "signature"); File.WriteAllBytes(signatureFileAndPath, signedData.GetEncoded()); }
private string SignMessage(string msg, bool isProd) { var gen = new CmsSignedDataGenerator(); X509Certificate2 certificate = GetCertificate(isProd); var privKey = DotNetUtilities.GetRsaKeyPair(certificate.GetRSAPrivateKey()).Private; var cert = DotNetUtilities.FromX509Certificate(certificate); gen.AddSigner(privKey, cert, CmsSignedDataGenerator.DigestSha1); var certX509 = DotNetUtilities.ToX509Certificate(cert.CertificateStructure); var certList = new List <Org.BouncyCastle.X509.X509Certificate>(); certList.Add(cert); X509CollectionStoreParameters PP = new X509CollectionStoreParameters(certList); IX509Store st1 = X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); gen.AddCertificates(st1); Encoding EncodedMsg = Encoding.UTF8; byte[] dataToSign = EncodedMsg.GetBytes(msg); CmsProcessable data = new CmsProcessableByteArray(dataToSign); CmsSignedData signed = gen.Generate(PkcsObjectIdentifiers.Pkcs7, data, true); var result = signed.GetEncoded(); return(Convert.ToBase64String(result)); }
/// <summary> /// Method that performs the signing process /// </summary> /// <param name="input"></param> /// <param name="parameters"></param> /// <param name="signedData"></param> /// <returns></returns> private SignatureDocument ComputeSignature(CmsProcessableByteArray content, SignatureParameters parameters, CmsSignedData signedData) { byte[] toBeSigned = ToBeSigned(content, parameters, signedData, false); byte[] signature = parameters.Signer.SignData(toBeSigned, parameters.DigestMethod); PreComputedSigner preComputedSigner = new PreComputedSigner(signature); CustomCMSSignedDataGenerator generator = CreateSignedGenerator(preComputedSigner, parameters, signedData); CmsSignedData newSignedData = null; if (parameters.SignaturePackaging == SignaturePackaging.ATTACHED_IMPLICIT && parameters.PreCalculatedDigest == null) { newSignedData = generator.Generate(content, true); } else { if (parameters.PreCalculatedDigest != null) { generator.PreCalculatedDigest = parameters.PreCalculatedDigest; newSignedData = generator.Generate(null, false); } else if (content != null) { newSignedData = generator.Generate(content, false); } else { generator.PreCalculatedDigest = GetDigestValue(signedData.GetSignerInfos(), parameters.DigestMethod); newSignedData = generator.Generate(null, false); } } return(new SignatureDocument(new CmsSignedData(newSignedData.GetEncoded()))); }
public byte[] Sign(byte[] cmsData) { IList certs = new List <X509Certificate>(); byte[] signBytes = File.ReadAllBytes(GetFile()); X509Certificate2 signCert = new X509Certificate2(signBytes, Key, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); certs.Add(DotNetUtilities.FromX509Certificate(signCert)); IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); AsymmetricCipherKeyPair pair = DotNetUtilities.GetKeyPair(signCert.PrivateKey); X509Certificate bX509Certificate = DotNetUtilities.FromX509Certificate(signCert); gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha1); gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha256); CmsSignedData unsignedData = new CmsSignedData(cmsData); gen.AddCertificates(x509Certs); CmsProcessable msg = new CmsProcessableByteArray(unsignedData.GetEncoded()); CmsSignedData cmsSignedData = gen.Generate(CmsSignedGenerator.Data, msg, true); byte[] p7MData = cmsSignedData.GetEncoded(); return(p7MData); }
private byte[] EncodeAndSign(string input) { var _signingCertificate = GetSigningCertificate(string.Empty); AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(_signingCertificate.PrivateKey); X509Certificate bouncy = new X509CertificateParser().ReadCertificate(_signingCertificate.GetRawCertData()); byte[] content = new UTF8Encoding().GetBytes(input); var signedDataGenerator = new CmsSignedDataGenerator(); var processableByteArray = new CmsProcessableByteArray(content); IList certCollection = new ArrayList(); var chain = new X509Chain(); chain.Build(_signingCertificate); foreach (X509ChainElement link in chain.ChainElements) { certCollection.Add(DotNetUtilities.FromX509Certificate(link.Certificate)); } IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters( certCollection)); signedDataGenerator.AddCertificates(certStore); signedDataGenerator.AddSigner(keyPair.Private, bouncy, CmsSignedGenerator.DigestSha1); CmsSignedData signedData = signedDataGenerator.Generate(processableByteArray, true); return(signedData.GetEncoded()); }
public virtual Stream OpenStream() { Stream output = new MemoryStream(); DerOutputStream derOuput = new DerOutputStream(output); derOuput.WriteObject(Asn1Object.FromByteArray(signedData.GetEncoded())); output.Seek(0, SeekOrigin.Begin); return(output); }
private void SignManigestFile(PassGeneratorRequest request) { Trace.TraceInformation("Signing the manifest file..."); X509Certificate2 card = GetCertificate(request); if (card == null) { throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct."); } X509Certificate2 appleCA = GetAppleCertificate(request); if (appleCA == null) { throw new FileNotFoundException("Apple Certficate could not be found. Please downloaad from http://www.apple.com/certificateauthority/ and install into your LOCAL MACHINE certificate store."); } try { Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; Trace.TraceInformation("Fetching Apple Certificate for signing.."); Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA); Trace.TraceInformation("Constructing the certificate chain.."); ArrayList intermediateCerts = new ArrayList(); intermediateCerts.Add(appleCert); intermediateCerts.Add(cert); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1); generator.AddCertificates(st1); Trace.TraceInformation("Processing the signature.."); CmsProcessable content = new CmsProcessableByteArray(manifestFile); CmsSignedData signedData = generator.Generate(content, false); signatureFile = signedData.GetEncoded(); Trace.TraceInformation("The file has been successfully signed!"); } catch (Exception exp) { Trace.TraceError("Failed to sign the manifest file: [{0}]", exp.Message); throw new ManifestSigningException("Failed to sign manifest", exp); } }
// Sign the message with the private key of the signer. static public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached, bool UsaTSA, string TSAurl, string TSAuser, string TSApass) { try { SHA256Managed hashSha256 = new SHA256Managed(); byte[] certHash = hashSha256.ComputeHash(signerCert.RawData); EssCertIDv2 essCert1 = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert1 }); Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(CertHAttribute); Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v); CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp(); var rsa = (RSACryptoServiceProvider)signerCert.PrivateKey; Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(signerCert); cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null); ArrayList certList = new ArrayList(); certList.Add(certCopy); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); cms.AddCertificates(st1); CmsProcessableByteArray file = new CmsProcessableByteArray(msg); //CmsProcessableFile(File); CmsSignedData Firmato = cms.Generate(file, false); //se settato a true, il secondo argomento integra l'intero file byte[] bb = Firmato.GetEncoded(); if (UsaTSA) { CmsSignedData sd = new CmsSignedData(bb); SignerInformationStore signers = sd.GetSignerInfos(); byte[] signature = null; SignerInformation signer = null; foreach (SignerInformation signer_ in signers.GetSigners()) { signer = signer_; break; } signature = signer.GetSignature(); Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass)); signer = SignerInformation.ReplaceUnsignedAttributes(signer, at); IList signerInfos = new ArrayList(); signerInfos.Add(signer); sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos)); bb = sd.GetEncoded(); } return(bb); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(null); } }
private byte[] TimestampAuthorityResponse(EstEIDReader estEidReader, byte[] signedPkcs) { ArrayList newSigners = new ArrayList(); CmsSignedData sd = new CmsSignedData(signedPkcs); foreach (SignerInformation si in sd.GetSignerInfos().GetSigners()) { // possible TSA URLs //string TsaServerUrl = "http://www.edelweb.fr/cgi-bin/service-tsp"; //string TsaServerUrl = "http://dse200.ncipher.com/TSS/HttpTspServer"; byte[] signedDigest = si.GetSignature(); byte[] timeStampHash = ComputeHash(estEidReader, signedDigest); string TsaServerUrl = stamp.Url; string TsaUser = stamp.User; string TsaPassword = stamp.Password; string error = string.Empty; byte[] timeStampToken = X509Utils.GetTimestampToken(TsaServerUrl, TsaUser, TsaPassword, timeStampHash, ref error); if (timeStampToken == null) { throw new Exception(Resources.TSA_ERROR + error); } Hashtable ht = new Hashtable(); Asn1Object derObj = new Asn1InputStream(timeStampToken).ReadObject(); DerSet derSet = new DerSet(derObj); Org.BouncyCastle.Asn1.Cms.Attribute unsignAtt = new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier(X509Utils.ID_TIME_STAMP_TOKEN), derSet); ht.Add(X509Utils.ID_TIME_STAMP_TOKEN, unsignAtt); Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAtts = new Org.BouncyCastle.Asn1.Cms.AttributeTable(ht); newSigners.Add(SignerInformation.ReplaceUnsignedAttributes(si, unsignedAtts)); } SignerInformationStore newSignerInformationStore = new SignerInformationStore(newSigners); CmsSignedData newSd = CmsSignedData.ReplaceSigners(sd, newSignerInformationStore); // Encode the CMS/PKCS #7 message return(newSd.GetEncoded()); }
/// <summary> /// The method used to sign data with private key. /// Signs the provided <code>data</code> and returns both data and /// the signature in a PKCS#7 container. /// https://csharp.hotexamples.com/examples/Org.BouncyCastle.Cms/CmsSignedDataGenerator/AddCrls/php-cmssigneddatagenerator-addcrls-method-examples.html /// </summary> /// <param name="data"></param> /// <param name="signCert"></param> /// <returns></returns> public static byte[] SignData(byte[] data, X509Certificate2 signCert) { IList certs = new List <Org.BouncyCastle.X509.X509Certificate>(); certs.Add(DotNetUtilities.FromX509Certificate(signCert)); IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); AsymmetricCipherKeyPair pair = DotNetUtilities.GetKeyPair(signCert.PrivateKey); Org.BouncyCastle.X509.X509Certificate bX509Certificate = DotNetUtilities.FromX509Certificate(signCert); gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha256); gen.AddCertificates(x509Certs); CmsProcessable msg = new CmsProcessableByteArray(data); CmsSignedData cmsSignedData = gen.Generate(CmsSignedGenerator.Data, msg, true); byte[] p7MData = cmsSignedData.GetEncoded(); return(p7MData); }
/// <exception cref="System.IO.IOException"></exception> public virtual Document ExtendSignatures(Document document, Document originalData , SignatureParameters parameters) { try { CmsSignedData signedData = new CmsSignedData(document.OpenStream()); SignerInformationStore signerStore = signedData.GetSignerInfos(); List <SignerInformation> siArray = new List <SignerInformation>(); foreach (SignerInformation si in signerStore.GetSigners()) { try { //jbonilla - Hack para evitar errores cuando una firma ya ha sido extendida. //Se asume que sólo se extiende las firmas desde BES. //TODO jbonilla - Se debería validar hasta qué punto se extendió (BES, T, C, X, XL). if (si.UnsignedAttributes.Count == 0) { siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData)); } else { //LOG.Error("Already extended?"); siArray.Add(si); } } catch (IOException) { //LOG.Error("Exception when extending signature"); siArray.Add(si); } } SignerInformationStore newSignerStore = new SignerInformationStore(siArray); CmsSignedData extended = CmsSignedData.ReplaceSigners(signedData, newSignerStore); return(new InMemoryDocument(extended.GetEncoded())); } catch (CmsException) { throw new IOException("Cannot parse CMS data"); } }
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 static SignedCms ModifyUnsignedAttributes(SignedCms signedCms, Func <AttributeTable, AttributeTable> modify) { byte[] bytes = signedCms.Encode(); var bcSignedCms = new CmsSignedData(bytes); SignerInformationStore signerInfos = bcSignedCms.GetSignerInfos(); SignerInformation signerInfo = GetFirstSignerInfo(signerInfos); AttributeTable updatedAttributes = modify(signerInfo.UnsignedAttributes); SignerInformation updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes); var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo); CmsSignedData updatedBcSignedCms = CmsSignedData.ReplaceSigners(bcSignedCms, updatedSignerInfos); var updatedSignedCms = new SignedCms(); updatedSignedCms.Decode(updatedBcSignedCms.GetEncoded()); return(updatedSignedCms); }
public static byte[] FirmaFileBouncy(byte[] data, X509Certificate2 cert) { try { SHA256Managed hashSha256 = new SHA256Managed(); byte[] certHash = hashSha256.ComputeHash(cert.RawData); EssCertIDv2 essCert1 = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert1 }); Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(CertHAttribute); Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v); CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp(); var rsa = (RSACryptoServiceProvider)cert.PrivateKey; Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert); cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null); ArrayList certList = new ArrayList(); certList.Add(certCopy); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); cms.AddCertificates(st1); //mi ricavo il file da firmare CmsSignedData Firmato = cms.Generate(new CmsProcessableByteArray(data), false); CmsSigner cmsSigner = new CmsSigner(cert); cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly; System.Security.Cryptography.Pkcs.ContentInfo contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(Firmato.GetEncoded()); SignedCms signedCms = new SignedCms(); signedCms.Decode(Firmato.GetEncoded()); byte[] ret = signedCms.Encode(); return(ret); } catch { return(null); } }
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); }
/// <summary> /// Generates the signed cms data. /// </summary> /// <returns>The signed cms data.</returns> /// <param name="signingData">Signing data.</param> /// <param name="signerCert">Signer certificate/</param> /// <param name="privateKey">Signer private key.</param> private static byte[] GenerateSignedCmsData(DerSet signingData, X509Certificate signerCert, AsymmetricKeyParameter privateKey) { CmsSignedDataGenerator cmsDataGenerator = new CmsSignedDataGenerator(); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(new X509Certificate[] { signerCert })); cmsDataGenerator.AddCertificates(x509Certs); Org.BouncyCastle.Asn1.Cms.AttributeTable attTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(signingData); cmsDataGenerator.AddSigner( privateKey, signerCert, SignerUtilities.GetObjectIdentifier(Sha256WithRsa).Id, Sha256Oid, new SimpleAttributeTableGenerator(attTable), null); CmsSignedData detachedSignedData = cmsDataGenerator.Generate(null, false); return(detachedSignedData.GetEncoded()); }
public byte[] GetSignedCms(Stream rangedStream) { rangedStream.Position = 0; CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator(); var cert = DotNetUtilities.FromX509Certificate(Certificate); var key = DotNetUtilities.GetKeyPair(Certificate.PrivateKey); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(new[] { cert })); signedDataGenerator.AddSigner(key.Private, cert, CmsSignedDataGenerator.DigestSha1); signedDataGenerator.AddCertificates(x509Certs); CmsProcessableInputStream msg = new CmsProcessableInputStream(rangedStream); CmsSignedData signedData = signedDataGenerator.Generate(msg, false); return(signedData.GetEncoded()); }
public static byte[] SignBC(string text, X509Certificate2 cert) { Org.BouncyCastle.X509.X509Certificate cert2 = DotNetUtilities.FromX509Certificate(cert); Org.BouncyCastle.Crypto.AsymmetricKeyParameter K = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private; CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(K, cert2, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha256); List <Org.BouncyCastle.X509.X509Certificate> certList = new List <Org.BouncyCastle.X509.X509Certificate>(); certList.Add(cert2); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); generator.AddCertificates(st1); byte[] data = Encoding.UTF8.GetBytes(text); CmsSignedData signedData = generator.Generate(new CmsProcessableByteArray(data), true); return(signedData.GetEncoded()); }
private byte[] SignWithCertificate(byte[] bytesToSign) { var generator = new CmsSignedDataGenerator(); var privKey = _gatewayKeyProvider.SigningPrivateKey; var certificate = _gatewayKeyProvider.SigningCertificate; var certificates = new List <Org.BouncyCastle.X509.X509Certificate>(); certificates.Add(certificate); var storeParameters = new X509CollectionStoreParameters(certificates); IX509Store store = X509StoreFactory.Create("Certificate/Collection", storeParameters); generator.AddSigner(privKey, certificate, CmsSignedGenerator.EncryptionRsa, CmsSignedGenerator.DigestSha256); generator.AddCertificates(store); var message = new CmsProcessableByteArray(bytesToSign); CmsSignedData signedData = generator.Generate(message, false); return(signedData.GetEncoded()); }
/// <exception cref="System.IO.IOException"></exception> public virtual Document ExtendSignature(object signatureId, Document document, Document originalData, SignatureParameters parameters) { SignerID toExtendId = (SignerID)signatureId; try { CmsSignedData signedData = new CmsSignedData(document.OpenStream()); SignerInformationStore signerStore = signedData.GetSignerInfos(); List <SignerInformation> siArray = new List <SignerInformation>(); //Iterator<object> infos = signerStore.GetSigners().Iterator(); IEnumerator infos = signerStore.GetSigners().GetEnumerator(); while (infos.MoveNext()) { SignerInformation si = (SignerInformation)infos.Current; if (si.SignerID.Equals(toExtendId)) { try { siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData)); } catch (IOException) { //LOG.Error("Exception when extending signature"); siArray.Add(si); } } } SignerInformationStore newSignerStore = new SignerInformationStore(siArray); CmsSignedData extended = CmsSignedData.ReplaceSigners(signedData, newSignerStore); return(new InMemoryDocument(extended.GetEncoded())); } catch (CmsException) { throw new IOException("Cannot parse CMS data"); } }
public byte[] FirmaFileBouncy(string NomeFile, X509Certificate2 cert, bool GiaFirmato, bool UsaTSA, string TSAurl, string TSAuser, string TSApass, out string RisFirma) { try { SHA256Managed hashSha256 = new SHA256Managed(); byte[] certHash = hashSha256.ComputeHash(cert.RawData); EssCertIDv2 essCert1 = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert1 }); Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(CertHAttribute); Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v); CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp(); var rsa = (RSACryptoServiceProvider)cert.PrivateKey; Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert); cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null); ArrayList certList = new ArrayList(); certList.Add(certCopy); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); cms.AddCertificates(st1); //mi ricavo il file da firmare FileInfo FileDaAprire = new FileInfo(NomeFile); /*CmsSignedData Firmato; * if (GiaFirmato) { * CmsSignedData signedData = new CmsSignedData(File.ReadAllBytes(NomeFile)); * if (signedData!=null){ * SignerInformationStore signers = signedData.GetSignerInfos(); * certList.Add(signers.GetSigners()); * //MessageBox.Show(signedData.ContentInfo.GetEncoded().Length.ToString()); * //signedData.ContentInfo.GetEncoded(); * } * certList.Insert(0,certCopy); * CmsProcessableByteArray file = new CmsProcessableByteArray(signedData.ContentInfo.GetEncoded()); * Firmato = cms.Generate(file, true); * } else { * certList.Add(certCopy); * CmsProcessableFile file = new CmsProcessableFile(FileDaAprire); * Firmato = cms.Generate(file, true); * } */ CmsProcessableFile file = new CmsProcessableFile(FileDaAprire); CmsSignedData Firmato = cms.Generate(file, true); byte[] Encoded = Firmato.GetEncoded(); if (UsaTSA) { CmsSignedData sd = new CmsSignedData(Encoded); SignerInformationStore signers = sd.GetSignerInfos(); byte[] signature = null; SignerInformation signer = null; foreach (SignerInformation signer_ in signers.GetSigners()) { signer = signer_; break; } signature = signer.GetSignature(); Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass)); signer = SignerInformation.ReplaceUnsignedAttributes(signer, at); IList signerInfos = new ArrayList(); signerInfos.Add(signer); sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos)); Encoded = sd.GetEncoded(); } RisFirma = ""; return(Encoded); } catch (Exception ex) { RisFirma = ex.ToString(); return(null); } }
public byte[] GetEncoded() { return(tsToken.GetEncoded()); }
public virtual bool CheckIntegrity(Document detachedDocument) { try { bool ret = false; SignerInformation si = null; if (detachedDocument != null) { // Recreate a SignerInformation with the content using a CMSSignedDataParser CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(detachedDocument.OpenStream()), _cmsSignedData.GetEncoded()); sp.GetSignedContent().Drain(); si = BCStaticHelpers.GetSigner(sp, signerInformation.SignerID); } else { si = signerInformation; } ret = si.Verify(SigningCertificate); return(ret); } catch (CertificateExpiredException) { return(false); } catch (CmsException) { return(false); } catch (IOException) { return(false); } }
public byte[] GetDocumentBytes() { return(_signedData.GetEncoded()); }
public virtual bool CheckIntegrity(Document detachedDocument) { //TODO jbonilla Verifier? //JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder // (); try { bool ret = false; SignerInformation si = null; if (detachedDocument != null) { // Recreate a SignerInformation with the content using a CMSSignedDataParser CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(detachedDocument .OpenStream()), cmsSignedData.GetEncoded()); sp.GetSignedContent().Drain(); si = sp.GetSignerInfos().GetFirstSigner(signerInformation.SignerID); } else { si = this.signerInformation; } //ret = si.Verify(verifier.Build(GetSigningCertificate())); ret = si.Verify(GetSigningCertificate()); return(ret); } /*catch (OperatorCreationException) * { * return false; * }*/ catch (CmsException) { return(false); } catch (IOException) { return(false); } }
/// <summary> /// Gets the byte representation of the ETK. /// </summary> /// <returns>Binary form of the ETK</returns> public byte[] GetEncoded() { return(raw.GetEncoded()); }