public void ComputeSignatureCmsSignerUnknown() { ContentInfo ci = new ContentInfo(asnNull); SignedCms sp = new SignedCms(ci); CmsSigner signer = new CmsSigner(SubjectIdentifierType.Unknown, GetCertificate(true)); signer.Certificates.Add(new X509Certificate2(intca_cer)); signer.Certificates.Add(new X509Certificate2(root_cer)); sp.ComputeSignature(signer); byte[] encoded = sp.Encode(); string s = BitConverter.ToString(encoded); #if DEBUG FileStream fs = File.OpenWrite("ComputeSignaturePkcs7SignerUnknown.der"); fs.Write(encoded, 0, encoded.Length); fs.Close(); #endif RoundTrip(encoded); }
public static void SignerInfo_AddRemoveUnsignedAttributes_JoinCounterSignaturesAttributesIntoOne() { byte[] message = { 1, 2, 3, 4, 5 }; ContentInfo content = new ContentInfo(message); SignedCms cms = new SignedCms(content); using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); cms.ComputeSignature(signer); } using (X509Certificate2 counterSigner1cert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) { CmsSigner counterSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner1cert); counterSigner.IncludeOption = X509IncludeOption.EndCertOnly; counterSigner.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1); cms.SignerInfos[0].ComputeCounterSignature(counterSigner); } using (X509Certificate2 counterSigner2cert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) { CmsSigner counterSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner2cert); cms.SignerInfos[0].ComputeCounterSignature(counterSigner); } Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[1].Values.Count); cms.CheckSignature(true); AsnEncodedData counterSignature = cms.SignerInfos[0].UnsignedAttributes[0].Values[0]; cms.SignerInfos[0].RemoveUnsignedAttribute(counterSignature); cms.SignerInfos[0].AddUnsignedAttribute(counterSignature); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); cms.CheckSignature(true); }
private static CmsSigner CreateCmsSigner(SignPackageRequest request) { // 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. CmsSigner signer; if (request.Certificate.Extensions[Oids.SubjectKeyIdentifier] == null) { signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, request.Certificate); } else { signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, request.Certificate); } request.BuildCertificateChainOnce(); var chain = request.Chain; foreach (var certificate in chain) { signer.Certificates.Add(certificate); } var attributes = SigningUtility.GetSignedAttributes(request, chain); foreach (var attribute in attributes) { signer.SignedAttributes.Add(attribute); } // We built the chain ourselves and added certificates. // Passing any other value here would trigger another chain build // and possibly add duplicate certs to the collection. signer.IncludeOption = X509IncludeOption.None; signer.DigestAlgorithm = request.SignatureHashAlgorithm.ConvertToOid(); return(signer); }
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); } }
public async Task RejectsMutuallyExclusiveCounterSignaturesCommitmentTypes(SignatureType[] counterSignatureTypes) { // Arrange var packageStream = await GetSignedPackageStream1Async(); ModifySignatureContent( packageStream, configuredSignedCms: signedCms => { using (var counterCertificate = SigningTestUtility.GenerateCertificate(subjectName: null, modifyGenerator: null)) { TestUtility.RequireSignedPackage(_corePackageService, _message.PackageId, counterCertificate.ComputeSHA256Thumbprint()); var cmsSigner = new CmsSigner(counterCertificate); foreach (var type in counterSignatureTypes) { cmsSigner.SignedAttributes.Add(AttributeUtility.CreateCommitmentTypeIndication(type)); } signedCms.SignerInfos[0].ComputeCounterSignature(cmsSigner); } }); // Act var result = await _target.ValidateAsync( _packageKey, _packageStream, _message, _token); // Assert VerifyPackageSigningStatus(result, ValidationStatus.Failed, PackageSigningStatus.Invalid); var issue = Assert.Single(result.Issues); Assert.Equal(ValidationIssueCode.ClientSigningVerificationFailure, issue.IssueCode); var typedIssue = Assert.IsType <ClientSigningVerificationFailure>(issue); Assert.Equal("NU3000", typedIssue.ClientCode); Assert.Equal("The commitment-type-indication attribute contains an invalid combination of values.", typedIssue.ClientMessage); }
public byte[] GetSignature(byte[] content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } var certificate = _CertificateProvider.GetCertificate(); if (!certificate.HasPrivateKey) { throw new InvalidOperationException($"Certificate does not have a private key - Subject:{certificate.Subject} Thumbprint:{certificate.Thumbprint}."); } var contentInfo = new ContentInfo(content); var signedCms = new SignedCms(contentInfo, true); var signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate) { IncludeOption = X509IncludeOption.EndCertOnly }; try { signedCms.ComputeSignature(signer); } catch (Exception e) { //NB. Cannot catch the internal exception type (cross-platform design of .NET Core) if (e.GetType().Name == "WindowsCryptographicException" && e.Message == "Keyset does not exist" && !WindowsIdentityQueries.CurrentUserIsAdministrator()) { throw new InvalidOperationException("Failed to sign with certificate when current user does not have UAC elevated permissions.", e); } throw; } return(signedCms.Encode()); }
/// <summary> /// Signs the message with a GOST digital signature and returns the attached signature (CMS format, base64 encoding). /// </summary> public static string ComputeAttachedSignature(X509Certificate2 certificate, byte[] message) { // The following line opens the private key. // It requires that the current user has permissions to use the private key. // Permissions are given using MMC console, Certificates snap-in. var privateKey = (GostAsymmetricAlgorithm)certificate.GetPrivateKeyAlgorithm(); var publicKey = (GostAsymmetricAlgorithm)certificate.GetPublicKeyAlgorithm(); // Create GOST-compliant signature helper var signedCms = new GostSignedCms(new ContentInfo(message), detached: false); // The object that has the signer information var signer = new CmsSigner(certificate); // Computing the CMS/PKCS#7 signature signedCms.ComputeSignature(signer, true); // Encoding the CMS/PKCS#7 message var encoded = signedCms.Encode(); return(Convert.ToBase64String(encoded)); }
/// <summary> /// Creates <see cref="SignedCms"/> for raw content and a collection of signing certificate /// </summary> /// <param name="content">The <c>byte</c> array to sign</param> /// <param name="signingCertificates">The certificates with which to sign.</param> /// <returns>An instance of <see cref="SignedCms"/> holdling the signatures</returns> public SignedCms CreateSignature(byte[] content, X509Certificate2Collection signingCertificates) { if (content == null) { throw new SignatureException(SignatureError.NullContent); } if (signingCertificates == null) { throw new SignatureException(SignatureError.NoCertificates); } SignedCms signature = new SignedCms(CreateDataContainer(content), true); // true: Detached Signature for (int i = 0, count = signingCertificates.Count; i < count; ++i) { CmsSigner signer = CreateSigner(signingCertificates[i]); signature.ComputeSignature(signer, true); // true: don't prompt the user } return(signature); }
/// <summary> /// Crea la firma CMS/PKCS #7 /// </summary> private static byte[] SignMsg(byte[] Message, SysX509.X509Certificate2 SignerCertificate, bool Detached) { //Creamos el contenedor ContentInfo contentInfo = new ContentInfo(Message); //Instanciamos el objeto SignedCms con el contenedor SignedCms objSignedCms = new SignedCms(contentInfo, Detached); //Creamos el "firmante" CmsSigner objCmsSigner = new CmsSigner(SignerCertificate); // Include the following line if the top certificate in the // smartcard is not in the trusted list. objCmsSigner.IncludeOption = SysX509.X509IncludeOption.EndCertOnly; // Sign the CMS/PKCS #7 message. The second argument is // needed to ask for the pin. objSignedCms.ComputeSignature(objCmsSigner, false); //Encodeamos el mensaje CMS/PKCS #7 return(objSignedCms.Encode()); }
public void TestArgumentExceptions() { var path = Path.Combine("..", "..", "TestData", "smime", "smime.p12"); var chain = new X509CertificateChain(); CmsSigner signer; using (var stream = File.OpenRead(path)) signer = new CmsSigner(stream, "no.secret"); Assert.Throws <ArgumentNullException> (() => new X509CertificateChain(null)); Assert.Throws <ArgumentNullException> (() => chain.Add(null)); Assert.Throws <ArgumentNullException> (() => chain.AddRange(null)); Assert.Throws <ArgumentNullException> (() => chain.Contains(null)); Assert.Throws <ArgumentNullException> (() => chain.CopyTo(null, 0)); Assert.Throws <ArgumentOutOfRangeException> (() => chain.CopyTo(new X509Certificate[0], -1)); Assert.Throws <ArgumentNullException> (() => chain.IndexOf(null)); Assert.Throws <ArgumentOutOfRangeException> (() => chain.Insert(-1, signer.Certificate)); Assert.Throws <ArgumentNullException> (() => chain.Insert(0, null)); Assert.Throws <ArgumentNullException> (() => chain[0] = null); Assert.Throws <ArgumentNullException> (() => chain.Remove(null)); Assert.Throws <ArgumentOutOfRangeException> (() => chain.RemoveAt(-1)); }
// This generates a package with a basic signed CMS. // The signature MUST NOT have any signed or unsigned attributes. public static async Task <FileInfo> SignPackageFileWithBasicSignedCmsAsync( TestDirectory directory, FileInfo packageFile, X509Certificate2 certificate) { SignatureContent signatureContent; using (var stream = packageFile.OpenRead()) using (var hashAlgorithm = HashAlgorithmName.SHA256.GetHashProvider()) { var hash = hashAlgorithm.ComputeHash(stream, leaveStreamOpen: false); signatureContent = new SignatureContent(SigningSpecifications.V1, HashAlgorithmName.SHA256, Convert.ToBase64String(hash)); } var signedPackageFile = new FileInfo(Path.Combine(directory, Guid.NewGuid().ToString())); var cmsSigner = new CmsSigner(certificate) { DigestAlgorithm = HashAlgorithmName.SHA256.ConvertToOid(), IncludeOption = X509IncludeOption.WholeChain }; var contentInfo = new ContentInfo(signatureContent.GetBytes()); var signature = new SignedCms(contentInfo); signature.ComputeSignature(cmsSigner); Assert.Empty(signature.SignerInfos[0].SignedAttributes); Assert.Empty(signature.SignerInfos[0].UnsignedAttributes); using (var packageReadStream = packageFile.OpenRead()) using (var packageWriteStream = signedPackageFile.OpenWrite()) using (var package = new SignedPackageArchive(packageReadStream, packageWriteStream)) using (var signatureStream = new MemoryStream(signature.Encode())) { await package.AddSignatureAsync(signatureStream, CancellationToken.None); } return(signedPackageFile); }
public static void SignaturePadding_InvalidValue() { RSASignaturePaddingMode badMode = (RSASignaturePaddingMode)(-1); // Currently we support all RSASignaturePaddings. However we want to make sure we fail properly // if an unsupported one is added later, so construct a bogus padding. RSASignaturePadding badPadding = (RSASignaturePadding)typeof(RSASignaturePadding) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, new Type[] { typeof(RSASignaturePaddingMode) }) .Invoke(new object[] { badMode }); // Test setter CmsSigner signer = new CmsSigner(); AssertExtensions.Throws <ArgumentException>("value", () => signer.SignaturePadding = badPadding); // Test ctor AssertExtensions.Throws <ArgumentException>("signaturePadding", () => new CmsSigner( SubjectIdentifierType.IssuerAndSerialNumber, certificate: null, privateKey: null, badPadding)); }
private static PrimarySignature CreateRepositoryCountersignature(CmsSigner cmsSigner, SignPackageRequest request, PrimarySignature primarySignature) { var cms = new SignedCms(); cms.Decode(primarySignature.GetBytes()); try { cms.SignerInfos[0].ComputeCounterSignature(cmsSigner); } catch (CryptographicException ex) when(ex.HResult == INVALID_PROVIDER_TYPE_HRESULT) { var exceptionBuilder = new StringBuilder(); exceptionBuilder.AppendLine(Strings.SignFailureCertificateInvalidProviderType); exceptionBuilder.AppendLine(CertificateUtility.X509Certificate2ToString(request.Certificate, Common.HashAlgorithmName.SHA256)); throw new SignatureException(NuGetLogCode.NU3001, exceptionBuilder.ToString()); } return(PrimarySignature.Load(cms)); }
/// <summary> /// Encodes the specified ar message. THIS IS FOR THE TEST CHANNEL /// </summary> /// <param name="arMessage">The ar message.</param> /// <param name="signerCert">The signer cert.</param> /// <param name="signerPassword">The signer password.</param> /// <returns></returns> internal static byte[] EncodeMDN(byte[] arMessage, string signerCert, string signerPassword) { byte[] signature = null; try { X509Certificate2 cert = new X509Certificate2(signerCert, signerPassword); ContentInfo contentInfo = new ContentInfo(arMessage); SignedCms signedCms = new SignedCms(contentInfo, true); CmsSigner cmsSigner = new CmsSigner(cert); signedCms.ComputeSignature(cmsSigner); signature = signedCms.Encode(); } catch (Exception ex) { Log.Error($"Encoding Exception occured : {ex.Message}"); } return(signature); }
private static byte[] CreateSignedDataPkcs7(byte[] encryptedMessageData, X509Certificate2 localPrivateKey) { // Create the outer envelope, signed with the local private key var signer = new CmsSigner(localPrivateKey) { DigestAlgorithm = Oids.Pkcs.MD5 }; // Message Type (messageType): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.2 // PKCS#10 request = PKCSReq (19) var messageType = new AsnEncodedData(Oids.Scep.MessageType, DerEncoding.EncodePrintableString("19")); signer.SignedAttributes.Add(messageType); // Tranaction ID (transId): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.1 var sha = new SHA512Managed(); var hashedKey = sha.ComputeHash(localPrivateKey.GetPublicKey()); var hashedKeyString = Convert.ToBase64String(hashedKey); var transactionId = new Pkcs9AttributeObject(Oids.Scep.TransactionId, DerEncoding.EncodePrintableString(hashedKeyString)); signer.SignedAttributes.Add(transactionId); // Sender Nonce (senderNonce): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.5 lastSenderNonce = new byte[16]; RNGCryptoServiceProvider.Create().GetBytes(lastSenderNonce); var nonce = new Pkcs9AttributeObject(Oids.Scep.SenderNonce, DerEncoding.EncodeOctet(lastSenderNonce)); signer.SignedAttributes.Add(nonce); // Seems that the oid is not needed for this envelope var signedContent = new ContentInfo(encryptedMessageData); //new Oid("1.2.840.113549.1.7.1", "data"), encryptedMessageData); var signedMessage = new SignedCms(signedContent); signedMessage.ComputeSignature(signer); var encodedMessage = signedMessage.Encode(); return(encodedMessage); }
public static byte[] SignFile(X509Certificate2 cert, byte[] data) { try { ContentInfo content = new ContentInfo(data); SignedCms signedCms = new SignedCms(content, false); if (VerifySign(data)) { signedCms.Decode(data); } CmsSigner signer = new CmsSigner(cert); signer.IncludeOption = X509IncludeOption.WholeChain; signedCms.ComputeSignature(signer); return(signedCms.Encode()); } catch (Exception ex) { throw new Exception("Erro ao assinar arquivo. A mensagem retornada foi: " + ex.Message); } }
static void Main(string[] args) { var data = Encoding.ASCII.GetBytes("Hi!"); var hash = HashAlgorithm.Create("SHA256").ComputeHash(data); var certificate = new X509Certificate2(Convert.FromBase64String(cert), pwd); // So since I've no idea how you got p7s, i improvised here: var cms = new SignedCms(new ContentInfo(hash), true); // true -> Detached var signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, certificate); cms.ComputeSignature(signer); var data2 = cms.Encode(); // assuming this was in p7s file var xx = Convert.ToBase64String(data2); // this passes, this is the .Net validation from OP var cms2 = new SignedCms(new ContentInfo(hash), true); cms2.Decode(Convert.FromBase64String(xx)); cms2.CheckSignature(true); // Same in bouncy castle: BCUtil.Validate(certificate, hash, xx); }
public static void SignWithImplicitSubjectKeyIdentifier() { byte[] contentBytes = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(contentBytes); SignedCms cms = new SignedCms(contentInfo, false); using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { // This cert has no Subject Key Identifier extension. Assert.Null(signerCert.Extensions[Oids.SubjectKeyIdentifier]); CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCert); cms.ComputeSignature(signer); } Assert.Equal( "6B4A6B92FDED07EE0119F3674A96D1A70D2A588D", (string)cms.SignerInfos[0].SignerIdentifier.Value); // Assert.NoThrow cms.CheckSignature(true); }
/// <summary> /// Firma mensaje /// </summary> /// <param name="argBytesMsg">Bytes del mensaje</param> /// <param name="argCertFirmante">Certificado usado para firmar</param> /// <returns>Bytes del mensaje firmado</returns> /// <remarks></remarks> public static byte[] FirmaBytesMensaje(byte[] argBytesMsg, X509Certificate2 argCertFirmante) { const string ID_FNC = "[FirmaBytesMensaje]"; try { // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms) var infoContenido = new ContentInfo(argBytesMsg); var cmsFirmado = new SignedCms(infoContenido); // Creo objeto CmsSigner que tiene las caracteristicas del firmante var cmsFirmante = new CmsSigner(argCertFirmante) { IncludeOption = X509IncludeOption.EndCertOnly }; if (VerboseMode) { Console.WriteLine($@"{ID_FNC}***Firmando bytes del mensaje..."); } // Firmo el mensaje PKCS #7 cmsFirmado.ComputeSignature(cmsFirmante); if (VerboseMode) { Console.WriteLine($@"{ID_FNC}***OK mensaje firmado"); } // Encodeo el mensaje PKCS #7. return(cmsFirmado.Encode()); } catch (Exception excepcionAlFirmar) { throw new Exception($"{ID_FNC}***Error al firmar: {excepcionAlFirmar.Message}"); } }
/// <summary> /// Generates a cryptographic signature for a given message /// </summary> /// <param name="message">The message to sign</param> /// <param name="signingCertificate">The certificate to sign the message with</param> /// <param name="encryptionCertificate">An optional encryption certificate to include along with the signature</param> /// <returns>The signature for the specified message</returns> internal static byte[] GetSignature(string message, X509Certificate2 signingCertificate, X509Certificate2 encryptionCertificate) { byte[] messageBytes = Encoding.ASCII.GetBytes(message); SignedCms signedCms = new SignedCms(new ContentInfo(messageBytes), true); CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate); cmsSigner.IncludeOption = X509IncludeOption.WholeChain; if (encryptionCertificate != null) { cmsSigner.Certificates.Add(encryptionCertificate); } Pkcs9SigningTime signingTime = new Pkcs9SigningTime(); cmsSigner.SignedAttributes.Add(signingTime); signedCms.ComputeSignature(cmsSigner, false); return(signedCms.Encode()); }
public static void CreateSignature_RsaPadding_DefaultToPkcs1() { ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3 }); SignedCms cms = new SignedCms(content); byte[] cmsBytes; using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert, null, null); cms.ComputeSignature(signer); cmsBytes = cms.Encode(); } cms = new SignedCms(); cms.Decode(cmsBytes); cms.CheckSignature(true); // Assert.NoThrow Assert.Single(cms.SignerInfos); SignerInfo signerInfo = cms.SignerInfos[0]; Assert.Equal(Oids.Rsa, signerInfo.SignatureAlgorithm.Value); }
//http://stackoverflow.com/questions/11526572/openssl-smime-in-c-sharp public static void Sign(string basePath) { var cert = new X509Certificate2(yourCertFile, yourCertFilePassword); var buffer = File.ReadAllBytes(Path.Combine(basePath, "manifest.json")); ContentInfo cont = new ContentInfo(buffer); var cms = new SignedCms(cont, true); var signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert); signer.IncludeOption = X509IncludeOption.ExcludeRoot; // TODO: You MUST visit this URL and download/install Apple's certificates // http://www.apple.com/certificateauthority/ // Apple Inc. Root Certificate // Apple Computer, Inc. Root Certificate // Worldwide Developer Relations cms.ComputeSignature(signer); var myCmsMessage = cms.Encode(); File.WriteAllBytes(Path.Combine(basePath, "signature"), myCmsMessage); }
public AsnElt Encode() { SignedCms signed = new SignedCms( new ContentInfo( IdPkInitAuthData, AuthPack.Encode().Encode() ) ); var signer = new CmsSigner(PKCert); if (!VerifyCerts) { signer.IncludeOption = X509IncludeOption.EndCertOnly; // only the end certificate is included in the X.509 chain information. } signed.ComputeSignature(signer, silent: false); return(AsnElt.Make(AsnElt.SEQUENCE, new AsnElt[] { AsnElt.Make(AsnElt.CONTEXT, 0, new AsnElt[] { AsnElt.MakeBlob(signed.Encode()) }) })); }
private static void VerifyWithExplicitPrivateKey(X509Certificate2 cert, AsymmetricAlgorithm key) { using (var pubCert = new X509Certificate2(cert.RawData)) { Assert.False(pubCert.HasPrivateKey); byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo); CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, pubCert, key) { IncludeOption = X509IncludeOption.EndCertOnly, DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1) }; cms.ComputeSignature(signer); cms.CheckSignature(true); Assert.Equal(1, cms.SignerInfos.Count); Assert.Equal(pubCert, cms.SignerInfos[0].Certificate); } }
public byte[] Sign(string certificateThumbprint, byte[] data, bool detached) { var store = new X509Store(StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false); if (certificates.Count == 0) { throw new Exception("Сертификат с отпечатком " + certificateThumbprint + " не найден в хранилище " + store.Location + ". Пользователь " + Environment.UserName); } var contentInfo = new ContentInfo(data); var signedCms = new SignedCms(contentInfo, detached); var cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificates[0]); cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now)); signedCms.ComputeSignature(cmsSigner, true); return(signedCms.Encode()); }
public async Task <byte[]> Handle(Stream file) { var data = await ReadFully(file); var envelopedCms = new EnvelopedCms(new ContentInfo(data)); envelopedCms.Encrypt(new CmsRecipient(cert)); var encryptedMessage = envelopedCms.Encode(); var signedCms = new SignedCms(new ContentInfo(encryptedMessage)); var signer = new CmsSigner(cert) { IncludeOption = X509IncludeOption.EndCertOnly }; signedCms.ComputeSignature(signer); var result = signedCms.Encode(); return(result); }
private byte[] Sign(byte[] data, X509Certificate2 signingCert) { // create ContentInfo ContentInfo content = new ContentInfo(data); // SignedCms represents signed data SignedCms signedMessage = new SignedCms(content); // create a signer CmsSigner signer = new CmsSigner(signingCert); // sign the data //Orig:signedMessage.ComputeSignature(signer); signedMessage.ComputeSignature(signer, false); // create PKCS #7 byte array byte[] signedBytes = signedMessage.Encode(); // return signed data return(signedBytes); }
/// <summary> /// Подписывает документ. /// </summary> /// <param name="userId">ИД пользователя.</param> /// <param name="seanceId">ИД сеанса (клиентского подключения).</param> /// <param name="certificateId">ИД сертификата.</param> /// <param name="document">Документ.</param> /// <param name="data">Подписываемые данные.</param> /// <param name="contentType">Тип подписываемых данных.</param> /// <returns>ИД операции.</returns> public string SignDocument(int userId, int seanceId, int certificateId, DocumentModel document, Stream data, ContentType contentType) { byte[] signature; using (var certificate = CertificateManager.GetUserCertificate(userId, certificateId)) { using (var ms = new MemoryStream()) { data.CopyTo(ms); var contentInfo = new ContentInfo(ms.ToArray()); var signedCms = new SignedCms(contentInfo, true); var cmsSigner = new CmsSigner(certificate); cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly; cmsSigner.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now)); signedCms.ComputeSignature(cmsSigner, true); signature = signedCms.Encode(); } } var newOperationId = Guid.NewGuid().ToString(); RequestResultsStorage.SaveRequestResult(userId, newOperationId, null); // Имитируем работу. Task.Delay(TimeSpan.FromSeconds(10)) .ContinueWith(t => { RequestResultsStorage.SaveRequestResult(userId, newOperationId, signature); }); return(newOperationId); }
/// <summary> /// Firma mensaje /// </summary> /// <param name="messageBytes">Bytes del mensaje</param> /// <param name="signerCertificate">Certificado usado para firmar</param> /// <returns>Bytes del mensaje firmado</returns> /// <remarks></remarks> public static byte[] SignMessageBytes(byte[] messageBytes, X509Certificate2 signerCertificate) { const string ID_FNC = "[FirmaBytesMensaje]"; try { // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms) var contentInfo = new ContentInfo(messageBytes); var signedCms = new SignedCms(contentInfo); // Creo objeto CmsSigner que tiene las caracteristicas del firmante var cmsSigner = new CmsSigner(signerCertificate) { IncludeOption = X509IncludeOption.EndCertOnly }; if (VerboseMode) { Console.WriteLine(ID_FNC + "***Firmando bytes del mensaje..."); } // Firmo el mensaje PKCS #7 signedCms.ComputeSignature(cmsSigner); if (VerboseMode) { Console.WriteLine(ID_FNC + "***OK mensaje firmado"); } // Encodeo el mensaje PKCS #7. return(signedCms.Encode()); } catch (Exception ex) { throw new Exception(ID_FNC + "***Error al firmar: " + ex.Message); } }
public void TestSignerIdentifierType() { var path = Path.Combine("..", "..", "TestData", "smime", "smime.p12"); List <X509Certificate> certificates; AsymmetricKeyParameter key; var password = "******"; CmsSigner signer; signer = new CmsSigner(path, password, SubjectIdentifierType.SubjectKeyIdentifier); Assert.AreEqual(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (string, string)"); Assert.AreEqual(RsaSignaturePaddingScheme.Pkcs1, signer.RsaSignaturePaddingScheme, "RsaSignaturePaddingScheme"); Assert.IsNull(signer.RsaSignaturePadding, "RsaSignaturePadding"); using (var stream = File.OpenRead(path)) signer = new CmsSigner(stream, password, SubjectIdentifierType.SubjectKeyIdentifier); Assert.AreEqual(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (Stream, string)"); Assert.AreEqual(RsaSignaturePaddingScheme.Pkcs1, signer.RsaSignaturePaddingScheme, "RsaSignaturePaddingScheme"); Assert.IsNull(signer.RsaSignaturePadding, "RsaSignaturePadding"); LoadPkcs12(path, password, out certificates, out key); signer = new CmsSigner(certificates, key, SubjectIdentifierType.SubjectKeyIdentifier); Assert.AreEqual(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (chain, key)"); Assert.AreEqual(RsaSignaturePaddingScheme.Pkcs1, signer.RsaSignaturePaddingScheme, "RsaSignaturePaddingScheme"); Assert.IsNull(signer.RsaSignaturePadding, "RsaSignaturePadding"); signer = new CmsSigner(certificates[0], key, SubjectIdentifierType.SubjectKeyIdentifier); Assert.AreEqual(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (certificate, key)"); Assert.AreEqual(RsaSignaturePaddingScheme.Pkcs1, signer.RsaSignaturePaddingScheme, "RsaSignaturePaddingScheme"); Assert.IsNull(signer.RsaSignaturePadding, "RsaSignaturePadding"); signer = new CmsSigner(new X509Certificate2(path, password, X509KeyStorageFlags.Exportable), SubjectIdentifierType.SubjectKeyIdentifier); Assert.AreEqual(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (X509Certificate2)"); Assert.AreEqual(RsaSignaturePaddingScheme.Pkcs1, signer.RsaSignaturePaddingScheme, "RsaSignaturePaddingScheme"); Assert.IsNull(signer.RsaSignaturePadding, "RsaSignaturePadding"); }
/// <summary> /// The <see cref="M:System.Security.Cryptography.Pkcs.SignerInfo.ComputeCounterSignature(System.Security.Cryptography.Pkcs.CmsSigner)"/> method creates a countersignature by using the specified signer and adds the signature to the CMS/PKCS #7 message. Countersignatures are restricted to one level. /// </summary> /// <param name="signer">A <see cref="T:System.Security.Cryptography.Pkcs.CmsSigner"/> object that represents the counter signer.</param><exception cref="T:System.ArgumentNullException">A null reference was passed to a method that does not accept it as a valid argument. </exception><exception cref="T:System.Security.Cryptography.CryptographicException">A cryptographic operation could not be completed.</exception> public void ComputeCounterSignature(CmsSigner signer) { if (this.m_parentSignerInfo != null) throw new CryptographicException(-2147483647); if (signer == null) throw new ArgumentNullException("signer"); if (signer.Certificate == null) signer.Certificate = PkcsUtils.SelectSignerCertificate(); if (!signer.Certificate.HasPrivateKey) throw new CryptographicException(-2146893811); this.CounterSign(signer); }
private bool signFile(string file, string outFile, string algoritmus, bool detached) { try { string saveTo = Path.GetDirectoryName(file); string tmpDir = FastZep.FastZepFolder + "tmp"; if (lbValue == "") { return false; } if (Directory.Exists(tmpDir)) { Directory.Delete(tmpDir, true); } Directory.CreateDirectory(tmpDir); string date = DateTime.Now.Subtract(TimeSpan.FromHours(1)).ToString("yyyyMMddHHmmss") + "Z"; Directory.CreateDirectory(tmpDir + "\\D" + date + "\\Policy\\"); string certFile = tmpDir + "\\D" + date + "\\Policy\\P" + date + ".der"; string sigFile = tmpDir + "\\D" + date + "\\S" + date + ".p7s"; string emlFile = tmpDir + "\\D" + date + "\\M" + date + ".eml"; Directory.CreateDirectory(tmpDir + "\\D" + date + "\\"); TextWriter eml = new StreamWriter(emlFile); eml.WriteLine("MIME-Version: 1.0"); eml.WriteLine("Content-Type: " + MimeType(file)); eml.WriteLine("Content-Transfer-Encoding: base64"); eml.WriteLine("Content-Disposition: filename=\"" + Path.GetFileName(file) + "\""); eml.WriteLine(); FileStream fs = new FileStream(file, FileMode.Open); byte[] filebytes = new byte[fs.Length]; fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks); eml.Write(encodedData); eml.Close(); fs.Close(); byte[] buffer = File.ReadAllBytes(emlFile); ContentInfo contentInfo = new ContentInfo(buffer); X509Store store = new X509Store(); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySerialNumber, lbValue, false); int i = 0; foreach (X509Certificate2 cert in certs) { i++; SignedCms signedCms = new SignedCms(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, !detached); CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert); cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime()); cmsSigner.IncludeOption = X509IncludeOption.WholeChain; ESSCertIDv2 cer2 = new ESSCertIDv2(cert); X509Chain chain = new X509Chain(); chain.Build(cert); /* /**/ //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.21", CertRefs.get(chain))); //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.22", CertCrls.get(chain))); //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.23", OtherCerts.get(chain))); //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.24", OtherCrls.get(chain))); /**/ //cmsSigner.SignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.47", cer2.get())); //cmsSigner.SignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.15", getPolicy(false))); /**/ signedCms.ComputeSignature(cmsSigner, false); File.WriteAllBytes(certFile, getPolicy(true)); File.WriteAllBytes(sigFile, signedCms.Encode()); } if (i == 0) { throw new Exception("Failed" + Marshal.GetLastWin32Error().ToString()); } SignedCms signedCms2 = new SignedCms(); byte[] encodedMessage = File.ReadAllBytes(sigFile); signedCms2.Decode(encodedMessage); BHI.Rats.RatsCompressionManager.Zip(tmpDir, outFile); Directory.Delete(tmpDir, true); return true; } catch (CryptographicException e) { var error = e.Message.ToString(); if (error == "Unknown error \"-1073741275\".") { error = "Nepodarilo sa načítať certifikát. odpojte a pripojte čítačku."; } if (error == "An internal error occurred.\r\n") { error = "Došlo ku chybe pri podpisovaní. Pravdepodobne nemáte pripojený USB kľúč alebo čítačku kariet."; } Console.WriteLine("Signing failed: " + error.ToString()); if (e.InnerException != null) { Console.WriteLine("Inner Exception: " + e.InnerException.ToString()); } MessageBox.Show(error, "Chyba pri podpisovaní", MessageBoxButtons.OK, MessageBoxIcon.Error); }catch (Exception exc) { MessageBox.Show(exc.Message + "\n" + Marshal.GetLastWin32Error().ToString(), "Chyba pri podpisovaní", MessageBoxButtons.OK, MessageBoxIcon.Error); } return false; }
/// <summary> /// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>. /// </summary> /// <returns>The cms signer.</returns> /// <param name="mailbox">The mailbox.</param> /// <param name="digestAlgo">The preferred digest algorithm.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected override CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo) { var store = new X509Store (StoreName.My, StoreLocation); store.Open (OpenFlags.ReadOnly); try { foreach (var certificate in store.Certificates) { if (!certificate.HasPrivateKey) continue; if (certificate.GetNameInfo (X509NameType.EmailName, false) != mailbox.Address) continue; var pair = DotNetUtilities.GetKeyPair (certificate.PrivateKey); var cert = DotNetUtilities.FromX509Certificate (certificate); var signer = new CmsSigner (cert, pair.Private); signer.DigestAlgorithm = digestAlgo; return signer; } } finally { store.Close (); } throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found."); }
public void ComputeCounterSignature(CmsSigner signer) { }
public void ComputeSignature(CmsSigner signer) { }
/// <summary> /// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>. /// </summary> /// <remarks> /// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>. /// </remarks> /// <returns>The cms signer.</returns> /// <param name="mailbox">The mailbox.</param> /// <param name="digestAlgo">The preferred digest algorithm.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo) { var certificate = GetCmsSignerCertificate (mailbox); var pair = DotNetUtilities.GetKeyPair (certificate.PrivateKey); var cert = DotNetUtilities.FromX509Certificate (certificate); var signer = new CmsSigner (cert, pair.Private); signer.DigestAlgorithm = digestAlgo; return signer; }
public void ComputeSignature(CmsSigner signer, bool silent) { }
/// <summary> /// Construye un Login Ticket obtenido del WSAA /// </summary> /// <param name="argServicio">Servicio al que se desea acceder</param> /// <param name="argUrlWsaa">URL del WSAA</param> /// <param name="argRutaCertX509Firmante">Ruta del certificado X509 (con clave privada) usado para firmar</param> /// <param name="argVerbose">Nivel detallado de descripcion? true/false</param> /// <remarks></remarks> public void Obtener(string argServicio, string argUrlWsaa, string argRutaCertX509Firmante, bool argVerbose) { RutaDelCertificadoFirmante = argRutaCertX509Firmante; string cmsFirmadoBase64; string respuesta; XmlNode xmlNodoUniqueId; XmlNode xmlNodoGenerationTime; XmlNode xmlNodoExpirationTime; XmlNode xmlNodoService; // PASO 1: Genero el Login Ticket Request try { solicitudXML = new XmlDocument (); solicitudXML.LoadXml (solicitudPlantillaXML); xmlNodoUniqueId = solicitudXML.SelectSingleNode ("//uniqueId"); xmlNodoGenerationTime = solicitudXML.SelectSingleNode ("//generationTime"); xmlNodoExpirationTime = solicitudXML.SelectSingleNode ("//expirationTime"); xmlNodoService = solicitudXML.SelectSingleNode ("//service"); var now = DateTime.Now; xmlNodoGenerationTime.InnerText = now.ToString ("s"); xmlNodoExpirationTime.InnerText = now.AddHours (12).ToString ("s"); xmlNodoUniqueId.InnerText = Convert.ToString (_globalUniqueID); xmlNodoService.InnerText = Servicio; _globalUniqueID += 1; } catch (Exception ex) { throw new Exception ("Error GENERANDO el Ticket de acceso : " + ex.Message); } // PASO 2: Firmo el Login Ticket Request try { // Convierto el login ticket request a bytes, para firmar Encoding EncodedMsg = Encoding.UTF8; byte[] msgBytes = EncodedMsg.GetBytes (solicitudXML.OuterXml); byte[] encodedSignedCms; // Firmo el msg y paso a Base64 try { var certList = new ArrayList (); CMSTypedData msg = new CMSProcessableByteArray ("Hello world!".getBytes ()); certList.add (signCert); Store certs = new JcaCertStore (certList); var gen = new CMSSignedDataGenerator (); ContentSigner sha1Signer = new JcaContentSignerBuilder ("SHA1withRSA").setProvider ("BC").build (signKP.getPrivate ()); gen.addSignerInfoGenerator ( new JcaSignerInfoGeneratorBuilder ( new JcaDigestCalculatorProviderBuilder ().setProvider ("BC").build ()) .build (sha1Signer, signCert)); gen.addCertificates (certs); CMSSignedData sigData = gen.generate (msg, false); cmsFirmadoBase64 = Convert.ToBase64String (encodedSignedCms); // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms) var infoContenido = new System.Security.Cryptography.Pkcs.ContentInfo (msgBytes); var cmsFirmado = new SignedCms (infoContenido); // Creo objeto CmsSigner que tiene las caracteristicas del firmante var cmsFirmante = new CmsSigner (certificadoFirmante); cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly; // Firmo el mensaje PKCS #7 cmsFirmado.ComputeSignature (cmsFirmante); // Encodeo el mensaje PKCS #7. encodedSignedCms = cmsFirmado.Encode (); } catch (Exception excepcionAlFirmar) { throw new Exception ("***Error al firmar: " + excepcionAlFirmar.Message); } } catch (Exception excepcionAlFirmar) { throw new Exception ("***Error FIRMANDO el LoginTicketRequest : " + excepcionAlFirmar.Message); } // PASO 3: Invoco al WSAA para obtener el Login Ticket Response try { var wsaa = new WSAA.LoginCMSService (); respuesta = wsaa.loginCms (cmsFirmadoBase64); } catch (Exception ex) { throw new Exception ("Error INVOCANDO al servicio WSAA : " + ex.Message); } // PASO 4: Analizo el Login Ticket Response recibido del WSAA try { respuestaXML = new XmlDocument (); respuestaXML.LoadXml (respuesta); id = UInt32.Parse (respuestaXML.SelectSingleNode ("//uniqueId").InnerText); generacion = DateTime.Parse (respuestaXML.SelectSingleNode ("//generationTime").InnerText); expiracion = DateTime.Parse (respuestaXML.SelectSingleNode ("//expirationTime").InnerText); firma = respuestaXML.SelectSingleNode ("//sign").InnerText; token = respuestaXML.SelectSingleNode ("//token").InnerText; } catch (Exception ex) { throw new Exception ("Error ANALIZANDO el LoginTicketResponse : " + ex.Message); } }
private void CounterSign(CmsSigner signer) { CspParameters parameters = new CspParameters(); if (!X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters)) throw new CryptographicException(Marshal.GetLastWin32Error()); KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); uint dwIndex = (uint)PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0); SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer); try { Marshal.StructureToPtr((object)signerEncodeInfo, localAllocHandle.DangerousGetHandle(), false); if (!CAPI.CryptMsgCountersign(this.m_signedCms.GetCryptMsgHandle(), dwIndex, 1U, localAllocHandle.DangerousGetHandle())) throw new CryptographicException(Marshal.GetLastWin32Error()); this.m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(localAllocHandle.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); localAllocHandle.Dispose(); signerEncodeInfo.Dispose(); } int num = (int)PkcsUtils.AddCertsToMessage(this.m_signedCms.GetCryptMsgHandle(), this.m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); }
public void ComputeSignature(CmsSigner signer) { this.ComputeSignature(signer, true); }
public void ComputeSignature(CmsSigner signer, bool silent) { if (signer == null) throw new ArgumentNullException("signer"); if (this.ContentInfo.Content.Length == 0) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content")); if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType) { if (this.m_safeCryptMsgHandle != null && !this.m_safeCryptMsgHandle.IsInvalid) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer")); this.Sign(signer, silent); } else { if (signer.Certificate == null) { if (silent) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound")); signer.Certificate = PkcsUtils.SelectSignerCertificate(); } if (!signer.Certificate.HasPrivateKey) throw new CryptographicException(-2146893811); CspParameters parameters = new CspParameters(); if (!X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters)) throw new CryptographicException(SignedCms.SafeGetLastWin32Error()); KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); if (this.m_safeCryptMsgHandle == null || this.m_safeCryptMsgHandle.IsInvalid) this.Sign(signer, silent); else this.CoSign(signer, silent); } }
private void CoSign(CmsSigner signer, bool silent) { CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer, silent); try { SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); try { Marshal.StructureToPtr((object)signerEncodeInfo, localAllocHandle.DangerousGetHandle(), false); if (!CAPI.CryptMsgControl(this.m_safeCryptMsgHandle, 0U, 6U, localAllocHandle.DangerousGetHandle())) throw new CryptographicException(Marshal.GetLastWin32Error()); } finally { Marshal.DestroyStructure(localAllocHandle.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); localAllocHandle.Dispose(); } } finally { signerEncodeInfo.Dispose(); } int num = (int)PkcsUtils.AddCertsToMessage(this.m_safeCryptMsgHandle, this.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); }
private unsafe void Sign(CmsSigner signer, bool silent) { CAPI.CMSG_SIGNED_ENCODE_INFO signedEncodeInfo = new CAPI.CMSG_SIGNED_ENCODE_INFO(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNED_ENCODE_INFO))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer, silent); byte[] encodedMessage = (byte[])null; try { SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(0U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); try { Marshal.StructureToPtr((object)signerEncodeInfo, localAllocHandle.DangerousGetHandle(), false); X509Certificate2Collection bagOfCertificates = PkcsUtils.CreateBagOfCertificates(signer); SafeLocalAllocHandle encodedCertBlob = PkcsUtils.CreateEncodedCertBlob(bagOfCertificates); signedEncodeInfo.cSigners = 1U; signedEncodeInfo.rgSigners = localAllocHandle.DangerousGetHandle(); signedEncodeInfo.cCertEncoded = (uint)bagOfCertificates.Count; if (bagOfCertificates.Count > 0) signedEncodeInfo.rgCertEncoded = encodedCertBlob.DangerousGetHandle(); SafeCryptMsgHandle safeCryptMsgHandle = string.Compare(this.ContentInfo.ContentType.Value, "1.2.840.113549.1.7.1", StringComparison.OrdinalIgnoreCase) != 0 ? CAPI.CryptMsgOpenToEncode(65537U, this.Detached ? 4U : 0U, 2U, new IntPtr((void*)&signedEncodeInfo), this.ContentInfo.ContentType.Value, IntPtr.Zero) : CAPI.CryptMsgOpenToEncode(65537U, this.Detached ? 4U : 0U, 2U, new IntPtr((void*)&signedEncodeInfo), IntPtr.Zero, IntPtr.Zero); if (safeCryptMsgHandle == null || safeCryptMsgHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); if (this.ContentInfo.Content.Length > 0 && !CAPI.CAPISafe.CryptMsgUpdate(safeCryptMsgHandle, this.ContentInfo.pContent, (uint)this.ContentInfo.Content.Length, true)) throw new CryptographicException(Marshal.GetLastWin32Error()); encodedMessage = PkcsUtils.GetContent(safeCryptMsgHandle); safeCryptMsgHandle.Dispose(); encodedCertBlob.Dispose(); } finally { Marshal.DestroyStructure(localAllocHandle.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); localAllocHandle.Dispose(); } } finally { signerEncodeInfo.Dispose(); } SafeCryptMsgHandle safeCryptMsgHandle1 = SignedCms.OpenToDecode(encodedMessage, this.ContentInfo, this.Detached); if (this.m_safeCryptMsgHandle != null && !this.m_safeCryptMsgHandle.IsInvalid) this.m_safeCryptMsgHandle.Dispose(); this.m_safeCryptMsgHandle = safeCryptMsgHandle1; GC.KeepAlive((object)signer); }