public TimeStampTokenGenerator(AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttr) { this.key = key; this.cert = cert; this.digestOID = digestOID; this.tsaPolicyOID = tsaPolicyOID; this.unsignedAttr = unsignedAttr; TspUtil.ValidateCertificate(cert); IDictionary dictionary; if (signedAttr != null) { dictionary = signedAttr.ToDictionary(); } else { dictionary = Platform.CreateHashtable(); } try { byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded()); EssCertID essCertID = new EssCertID(hash); Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertID))); dictionary[attribute.AttrType] = attribute; } catch (CertificateEncodingException e) { throw new TspException("Exception processing certificate.", e); } catch (SecurityUtilityException e2) { throw new TspException("Can't find a SHA-1 implementation.", e2); } this.signedAttr = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary); }
public virtual string[] GetClaimedSignerRoles() { if (signerInformation.SignedAttributes == null) { return(null); } BcCms.Attribute signerAttrAttr = signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr]; if (signerAttrAttr == null) { return(null); } SignerAttribute signerAttr = null; signerAttr = SignerAttribute.GetInstance(signerAttrAttr.AttrValues[0]); if (signerAttr == null) { return(null); } string[] ret = new string[signerAttr.ClaimedAttributes.Count]; for (int i = 0; i < signerAttr.ClaimedAttributes.Count; i++) { if (signerAttr.ClaimedAttributes[i] is DerOctetString) { ret[i] = Sharpen.Runtime.GetStringForBytes(((DerOctetString)signerAttr.ClaimedAttributes[i]) .GetOctets()); } else { ret[i] = signerAttr.ClaimedAttributes[i].ToString(); } } return(ret); }
public void GetNuGetPackageOwners_WithMultipleAttributes_Throws() { using (var certificate = _fixture.GetDefaultCertificate()) { var attributes = CreateAttributeCollection(certificate, _fixture.DefaultKeyPair.Private, vector => { var attribute = new BcAttribute( new DerObjectIdentifier(Oids.NuGetPackageOwners), new DerSet( new DerSequence( new DerUtf8String("a"), new DerUtf8String("b"), new DerUtf8String("c")))); vector.Add(attribute); vector.Add(attribute); }); var exception = Assert.Throws <CryptographicException>( () => AttributeUtility.GetNuGetPackageOwners(attributes)); Assert.Equal("Multiple 1.3.6.1.4.1.311.84.2.1.1.2 attributes are not allowed.", exception.Message); } }
private void AddAttribute(Org.BouncyCastle.Asn1.Cms.Attribute a) { DerObjectIdentifier attrType = a.AttrType; object obj = attributes[attrType]; if (obj == null) { attributes[attrType] = a; return; } IList list; if (obj is Org.BouncyCastle.Asn1.Cms.Attribute) { list = Platform.CreateArrayList(); list.Add(obj); list.Add(a); } else { list = (IList)obj; list.Add(a); } attributes[attrType] = list; }
private Asn1Object GetSingleValuedSignedAttribute(DerObjectIdentifier attrOID, string printableName) { Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = this.UnsignedAttributes; if (unsignedAttributes != null && unsignedAttributes.GetAll(attrOID).Count > 0) { throw new CmsException("The " + printableName + " attribute MUST NOT be an unsigned attribute"); } Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttributes = this.SignedAttributes; if (signedAttributes == null) { return(null); } Asn1EncodableVector all = signedAttributes.GetAll(attrOID); switch (all.Count) { case 0: return(null); case 1: { Org.BouncyCastle.Asn1.Cms.Attribute attribute = (Org.BouncyCastle.Asn1.Cms.Attribute)all[0]; Asn1Set attrValues = attribute.AttrValues; if (attrValues.Count != 1) { throw new CmsException("A " + printableName + " attribute MUST have a single attribute value"); } return(attrValues[0].ToAsn1Object()); } default: throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the " + printableName + " attribute"); } }
private IList <TimestampToken> GetTimestampList(DerObjectIdentifier attrType, TimestampToken.TimestampType timestampType) { if (signerInformation.UnsignedAttributes != null) { BcCms.Attribute timeStampAttr = signerInformation.UnsignedAttributes[attrType]; if (timeStampAttr == null) { return(null); } IList <TimestampToken> tstokens = new List <TimestampToken>(); foreach (Asn1Encodable value in timeStampAttr.AttrValues.ToArray()) { try { TimeStampToken token = new TimeStampToken(new CmsSignedData(value.GetDerEncoded())); tstokens.Add(new TimestampToken(token, timestampType)); } catch (Exception e) { throw new Exception("Parsing error", e); } } return(tstokens); } else { return(null); } }
/// <summary> /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the /// provided. /// </summary> /// <remarks> /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the /// provided. The hashing is performed by the method using the specified algorithm and a BouncyCastle provider. /// </remarks> /// <param name="signedData"></param> /// <exception cref="System.Exception">System.Exception</exception> protected internal virtual BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid , ITspSource tsa, AlgorithmIdentifier digestAlgorithm, byte[] messageImprint) { try { //jbonilla Hack para obtener el digest del TSA IDigest digest = null; string algorithmName = null; digest = DigestUtilities.GetDigest(DigestAlgorithm.SHA1.GetName()); algorithmName = DigestAlgorithm.SHA1.GetName(); digest.BlockUpdate(messageImprint, 0, messageImprint.Length); byte[] r = new byte[digest.GetDigestSize()]; digest.DoFinal(r, 0); byte[] toTimeStamp = r; TimeStampResponse tsresp = tsa.GetTimeStampResponse(DigestAlgorithm.GetByName(algorithmName) , toTimeStamp); TimeStampToken tstoken = tsresp.TimeStampToken; if (tstoken == null) { throw new ArgumentNullException("The TimeStampToken returned for the signature time stamp was empty." ); } BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray (tstoken.GetEncoded()))); return(signatureTimeStamp); } catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
public async Task Timestamps_WithTwoAttributesAndOneValueEach_ReturnsTwoTimestamps() { var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var nupkg = new SimpleTestPackageContext(); using (var packageStream = await nupkg.CreateAsStreamAsync()) using (var testCertificate = new X509Certificate2(_testFixture.TrustedTestCertificate.Source.Cert)) { AuthorPrimarySignature authorSignature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync( testCertificate, packageStream, timestampProvider); SignedCms updatedSignedCms = ModifyUnsignedAttributes(authorSignature.SignedCms, attributeTable => { BcAttribute attribute = attributeTable[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; Asn1Encodable value = attribute.AttrValues.ToArray().Single(); AttributeTable updatedAttributes = attributeTable.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, value); return(updatedAttributes); }); AssertTimestampAttributeAndValueCounts(updatedSignedCms, expectedAttributesCount: 2, expectedValuesCount: 2); var updatedAuthorSignature = new AuthorPrimarySignature(updatedSignedCms); Assert.Equal(2, updatedAuthorSignature.Timestamps.Count); } }
public AttributeTable(Asn1Set s) { attributes = Platform.CreateHashtable(s.Count); for (int i = 0; i != s.Count; i++) { Org.BouncyCastle.Asn1.Cms.Attribute instance = Org.BouncyCastle.Asn1.Cms.Attribute.GetInstance(s[i]); AddAttribute(instance); } }
public AttributeTable(Asn1EncodableVector v) { attributes = Platform.CreateHashtable(v.Count); foreach (Asn1Encodable item in v) { Org.BouncyCastle.Asn1.Cms.Attribute instance = Org.BouncyCastle.Asn1.Cms.Attribute.GetInstance(item); AddAttribute(instance); } }
/// <summary> /// Método para crear el atributo que contiene el rol del firmante /// </summary> /// <param name="parameters"></param> /// <returns></returns> private BcCms.Attribute MakeSignerAttrAttribute(SignatureParameters parameters) { DerUtf8String[] roles = new DerUtf8String[1]; roles[0] = new DerUtf8String(parameters.SignerRole); BcCms.Attribute claimedRolesAttr = new BcCms.Attribute(X509ObjectIdentifiers.id_at_name, new DerSet(roles)); return(new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsSignerAttr, new DerSet(new SignerAttribute (new DerSequence(claimedRolesAttr))))); }
private BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid , TimeStampClient tsa, DigestMethod digestMethod, byte[] messageImprint) { byte[] toTimeStamp = digestMethod.CalculateDigest(messageImprint); byte[] timeStampToken = tsa.GetTimeStamp(toTimeStamp, digestMethod, true); BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray (timeStampToken))); return(signatureTimeStamp); }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); DerObjectIdentifier attributeId = null; ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); switch (GetExtendedValidationType()) { case 1: { attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp; toTimestamp.Write(si.GetSignature()); // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5, // NOTE 2) toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] .AttrValues.GetDerEncoded()); break; } case 2: { attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp; break; } default: { throw new InvalidOperationException("CAdES-X Profile: Extended validation is set but no valid type (1 or 2)" ); } } toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs] .AttrValues.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs] .AttrValues.GetDerEncoded()); //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, GetSignatureTsa( ), digestAlgorithm, toTimestamp.ToByteArray()); //unsignedAttrHash.Put(attributeId, extendedTimeStamp); unsignedAttrHash.Add(attributeId, extendedTimeStamp); return(SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash ))); }
private byte[] GetEContent() { SignerInfo signerInfo = GetSignerInfo(); Asn1Set signedAttributesSet = signerInfo.AuthenticatedAttributes; ContentInfo contentInfo = _signedData.EncapContentInfo; byte[] contentBytes = ((DerOctetString)contentInfo.Content).GetOctets(); if (signedAttributesSet.Count == 0) // signed attributes absent, return content to be signed { return(contentBytes); } else // Signed attributes present (i.e. a structure containing a hash of the content), return that structure to be signed... // This option is taken by ICAO passports. { byte[] attributeBytes = signedAttributesSet.GetDerEncoded(); string digAlg = signerInfo.DigestAlgorithm.ObjectID.Id; // We'd better check that the content actually digests to the hash value contained! ;) IEnumerator attributes = signedAttributesSet.GetEnumerator(); byte[] storedDigestedContent = null; while (attributes.MoveNext()) { Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute((Asn1Sequence)attributes.Current); DerObjectIdentifier attrType = attribute.AttrType; if (attrType.Equals(RFC_3369_MESSAGE_DIGEST_OID)) { Asn1Set attrValueSet = attribute.AttrValues; if (attrValueSet.Count != 1) { Console.WriteLine("WARNING: expected only one attribute value in signedAttribute message diegest in eContent!"); } storedDigestedContent = ((DerOctetString)attrValueSet[0]).GetOctets(); } } if (storedDigestedContent == null) { Console.WriteLine("WARNING: error extracting signedAttribute message digest in eContent!"); } byte[] computedDigestedContent = SHA256.Create().ComputeHash(contentBytes); if (!Compare(storedDigestedContent, computedDigestedContent)) { Console.WriteLine("WARNING: error checking signedAttribute message digest in eContent!"); } return(attributeBytes); } }
/// <summary> /// Método que busca en las demás firmas el tipo de contenido firmado /// </summary> /// <param name="siStore"></param> /// <returns></returns> private BcCms.Attribute GetContentHintAttribute(SignerInformationStore siStore) { var signers = siStore.GetSigners(); foreach (SignerInformation signerInfo in signers) { BcCms.Attribute contentHint = signerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAAContentHint]; if (contentHint != null) { return(contentHint); } } return(null); }
/// <summary> /// Método que devuelve los atributos que deberán ser firmados /// </summary> /// <param name="parameters"></param> /// <returns></returns> private Dictionary <DerObjectIdentifier, Asn1Encodable> GetSignedAttributes(SignatureParameters parameters) { Dictionary <DerObjectIdentifier, Asn1Encodable> signedAttrs = new Dictionary <DerObjectIdentifier, Asn1Encodable>(); BcCms.Attribute signingCertificateReference = MakeSigningCertificateAttribute(parameters); signedAttrs.Add((DerObjectIdentifier)signingCertificateReference.AttrType, signingCertificateReference); signedAttrs.Add(PkcsObjectIdentifiers.Pkcs9AtSigningTime, MakeSigningTimeAttribute (parameters)); if (parameters.SignaturePolicyInfo != null) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, MakeSignaturePolicyAttribute(parameters)); } if (!string.IsNullOrEmpty(parameters.SignerRole)) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSignerAttr, MakeSignerAttrAttribute(parameters)); } if (parameters.SignatureProductionPlace != null) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSignerLocation, MakeSignerLocationAttribute(parameters)); } if (parameters.SignatureCommitments.Count > 0) { var commitments = MakeCommitmentTypeIndicationAttributes(parameters); foreach (var item in commitments) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsCommitmentType, item); } } if (!string.IsNullOrEmpty(parameters.MimeType)) { ContentHints contentHints = new ContentHints(new DerObjectIdentifier(MimeTypeHelper.GetMimeTypeOid(parameters.MimeType))); BcCms.Attribute contentAttr = new BcCms.Attribute(PkcsObjectIdentifiers.IdAAContentHint, new DerSet(contentHints)); signedAttrs.Add(PkcsObjectIdentifiers.IdAAContentHint, contentAttr); } return(signedAttrs); }
private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime?requestTimestamp = null) { var signCertAlias = signCertificate.Aliases.Cast <string>().First(signCertificate.IsKeyEntry); var signCertEntry = signCertificate.GetCertificate(signCertAlias); var signCert = signCertEntry.Certificate; var signPkEntry = signCertificate.GetKey(signCertAlias); var signPk = signPkEntry.Key; string digestName; if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id) { digestName = "SHA1"; } else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id) { digestName = "SHA256"; } else { throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}"); } var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id; var digest = DigestUtilities.CalculateDigest(digestName, data); var signedAttrs = new Dictionary <object, object>() { { CmsAttributeTableParameter.Digest, digest } }; if (requestTimestamp.HasValue) { var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime()))); signedAttrs.Add(signTimestamp.AttrType, signTimestamp); } var signedAttrGen = new DefaultSignedAttributeTableGenerator(); var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs); var generator = new CmsSignedDataGenerator(); generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null); var signedData = generator.Generate(new CmsProcessableByteArray(data), true); return(signedData.GetEncoded()); }
/// <summary> /// Método que busca en las demás firmas el message-digest que coincida con el algoritmo de huella dado /// </summary> /// <param name="siStore"></param> /// <param name="digestMethod"></param> /// <returns></returns> private byte[] GetDigestValue(SignerInformationStore siStore, DigestMethod digestMethod) { var signers = siStore.GetSigners(); foreach (SignerInformation signerInfo in signers) { if (signerInfo.DigestAlgOid == digestMethod.Oid) { BcCms.Attribute digest = signerInfo.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest]; DerOctetString derHash = (DerOctetString)digest.AttrValues[0]; return(derHash.GetOctets()); } } return(null); }
public TimeStampToken(CmsSignedData signedData) { tsToken = signedData; if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo)) { throw new TspValidationException("ContentInfo object not for a time stamp."); } ICollection signers = tsToken.GetSignerInfos().GetSigners(); if (signers.Count != 1) { throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature."); } IEnumerator enumerator = signers.GetEnumerator(); enumerator.MoveNext(); tsaSignerInfo = (SignerInformation)enumerator.Current; try { CmsProcessable signedContent = tsToken.SignedContent; MemoryStream memoryStream = new MemoryStream(); signedContent.Write(memoryStream); tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(memoryStream.ToArray()))); Org.BouncyCastle.Asn1.Cms.Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate]; if (attribute != null) { SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0])); } else { attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]; if (attribute == null) { throw new TspValidationException("no signing certificate attribute found, time stamp invalid."); } SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0])); } } catch (CmsException ex) { throw new TspException(ex.Message, ex.InnerException); } }
//internal override IDictionary<DerObjectIdentifier, Asn1Encodable> GetSignedAttributes internal override IDictionary GetSignedAttributes (SignatureParameters parameters) { try { //IDictionary<DerObjectIdentifier, Asn1Encodable> signedAttrs = base.GetSignedAttributes(parameters); IDictionary signedAttrs = base.GetSignedAttributes(parameters); Attribute policy = null; SignaturePolicyIdentifier sigPolicy = null; switch (parameters.SignaturePolicy) { case SignaturePolicy.EXPLICIT: { sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(new DerObjectIdentifier (parameters.SignaturePolicyID), new OtherHashAlgAndValue(new AlgorithmIdentifier (DigestAlgorithm.GetByName(parameters.SignaturePolicyHashAlgo).GetOid()), new DerOctetString(parameters.SignaturePolicyHashValue)))); policy = new Attribute(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(sigPolicy )); signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, policy); break; } case SignaturePolicy.IMPLICIT: { sigPolicy = new SignaturePolicyIdentifier(); //sigPolicy.IsSignaturePolicyImplied(); TODO jbonilla - validar policy = new Attribute(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(sigPolicy )); signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, policy); break; } case SignaturePolicy.NO_POLICY: { break; } } return signedAttrs; } catch (NoSuchAlgorithmException ex) { throw new ProfileException(ex.Message); } }
protected virtual IDictionary CreateStandardAttributeTable(IDictionary parameters) { IDictionary dictionary = Platform.CreateHashtable(this.table); if (!dictionary.Contains(CmsAttributes.ContentType)) { DerObjectIdentifier obj = (DerObjectIdentifier)parameters[CmsAttributeTableParameter.ContentType]; Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.ContentType, new DerSet(obj)); dictionary[attribute.AttrType] = attribute; } if (!dictionary.Contains(CmsAttributes.MessageDigest)) { byte[] str = (byte[])parameters[CmsAttributeTableParameter.Digest]; Org.BouncyCastle.Asn1.Cms.Attribute attribute2 = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.MessageDigest, new DerSet(new DerOctetString(str))); dictionary[attribute2.AttrType] = attribute2; } return(dictionary); }
/// <summary> /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the /// provided. /// </summary> /// <remarks> /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the /// provided. The hashing is performed by the method using the specified algorithm and a BouncyCastle provider. /// </remarks> /// <param name="signedData"></param> /// <exception cref="System.Exception">System.Exception</exception> protected internal virtual BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid , ITspSource tsa, AlgorithmIdentifier digestAlgorithm, byte[] messageImprint) { try { //jbonilla Hack para obtener el digest del TSA IDigest digest = null; string algorithmName = null; if (tsa is ITSAClient) { //TODO jbonilla - ¿AlgorithmIdentifier? digest = ((ITSAClient)tsa).GetMessageDigest(); algorithmName = digest.AlgorithmName; } else { digest = DigestUtilities.GetDigest(DigestAlgorithm.SHA1.GetName()); algorithmName = DigestAlgorithm.SHA1.GetName(); } byte[] toTimeStamp = DigestAlgorithms.Digest(digest, messageImprint); TimeStampResponse tsresp = tsa.GetTimeStampResponse(DigestAlgorithm.GetByName(algorithmName) , toTimeStamp); TimeStampToken tstoken = tsresp.TimeStampToken; if (tstoken == null) { throw new ArgumentNullException("The TimeStampToken returned for the signature time stamp was empty." ); } BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray (tstoken.GetEncoded()))); return(signatureTimeStamp); } catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
public void Validate(TimeStampRequest request) { TimeStampToken timeStampToken = TimeStampToken; if (timeStampToken != null) { TimeStampTokenInfo timeStampInfo = timeStampToken.TimeStampInfo; if (request.Nonce != null && !request.Nonce.Equals(timeStampInfo.Nonce)) { throw new TspValidationException("response contains wrong nonce value."); } if (Status != 0 && Status != 1) { throw new TspValidationException("time stamp token found in failed request."); } if (!Arrays.ConstantTimeAreEqual(request.GetMessageImprintDigest(), timeStampInfo.GetMessageImprintDigest())) { throw new TspValidationException("response for different message imprint digest."); } if (!timeStampInfo.MessageImprintAlgOid.Equals(request.MessageImprintAlgOid)) { throw new TspValidationException("response for different message imprint algorithm."); } Org.BouncyCastle.Asn1.Cms.Attribute attribute = timeStampToken.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate]; Org.BouncyCastle.Asn1.Cms.Attribute attribute2 = timeStampToken.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]; if (attribute == null && attribute2 == null) { throw new TspValidationException("no signing certificate attribute present."); } if (attribute == null) { } if (request.ReqPolicy != null && !request.ReqPolicy.Equals(timeStampInfo.Policy)) { throw new TspValidationException("TSA policy wrong for request."); } } else if (Status == 0 || Status == 1) { throw new TspValidationException("no time stamp token found and one expected."); } }
private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary std) { if (parameters.Contains(CmsAttributeTableParameter.ContentType) && !std.Contains(CmsAttributes.ContentType)) { DerObjectIdentifier obj = (DerObjectIdentifier)parameters[CmsAttributeTableParameter.ContentType]; Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.ContentType, new DerSet(obj)); std[attribute.AttrType] = attribute; } if (!std.Contains(CmsAttributes.SigningTime)) { Org.BouncyCastle.Asn1.Cms.Attribute attribute2 = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(DateTime.UtcNow))); std[attribute2.AttrType] = attribute2; } if (!std.Contains(CmsAttributes.MessageDigest)) { byte[] str = (byte[])parameters[CmsAttributeTableParameter.Digest]; Org.BouncyCastle.Asn1.Cms.Attribute attribute3 = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.MessageDigest, new DerSet(new DerOctetString(str))); std[attribute3.AttrType] = attribute3; } }
public void GetNuGetV3ServiceIndexUrl_WithMultipleAttributes_Throws() { using (var certificate = _fixture.GetDefaultCertificate()) { var attributes = CreateAttributeCollection(certificate, _fixture.DefaultKeyPair.Private, vector => { var attribute = new BcAttribute( new DerObjectIdentifier(Oids.NuGetV3ServiceIndexUrl), new DerSet(new DerIA5String("https://test.test"))); vector.Add(attribute); vector.Add(attribute); }); var exception = Assert.Throws <CryptographicException>( () => AttributeUtility.GetNuGetV3ServiceIndexUrl(attributes)); Assert.Equal("Multiple 1.3.6.1.4.1.311.84.2.1.1.1 attributes are not allowed.", exception.Message); } }
protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); using (var toTimestamp = new MemoryStream()) { DerObjectIdentifier attributeId; switch (GetExtendedValidationType()) { case 1: { attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp; toTimestamp.Write(si.GetSignature()); // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5, // NOTE 2) toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrValues.GetDerEncoded()); break; } case 2: { attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp; break; } default: { return(si); } } toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs].AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs].AttrValues.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs].AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs].AttrValues.GetDerEncoded()); var unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, SignatureTsa, toTimestamp.ToArray()); unsignedAttrHash.Add(attributeId, extendedTimeStamp); return(SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash))); } }
public void GetNuGetV3ServiceIndexUrl_WithMultipleAttributeValues_Throws() { using (var certificate = _fixture.GetDefaultCertificate()) { var attributes = CreateAttributeCollection(certificate, _fixture.DefaultKeyPair.Private, vector => { var value = new DerIA5String("https://test.test"); var attribute = new BcAttribute( new DerObjectIdentifier(Oids.NuGetV3ServiceIndexUrl), new DerSet(value, value)); vector.Add(attribute); }); var exception = Assert.Throws <SignatureException>( () => AttributeUtility.GetNuGetV3ServiceIndexUrl(attributes)); Assert.Equal( "The nuget-v3-service-index-url attribute must have exactly one attribute value.", exception.Message); } }
public virtual IList <CertificateRef> GetCertificateRefs() { IList <CertificateRef> list = new List <CertificateRef>(); if (signerInformation.UnsignedAttributes != null) { BcCms.Attribute completeCertRefsAttr = signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs]; if (completeCertRefsAttr != null && completeCertRefsAttr.AttrValues.Count > 0) { DerSequence completeCertificateRefs = (DerSequence)completeCertRefsAttr.AttrValues[0]; for (int i1 = 0; i1 < completeCertificateRefs.Count; i1++) { OtherCertID otherCertId = OtherCertID.GetInstance(completeCertificateRefs[i1]); CertificateRef certId = new CertificateRef(); certId.SetDigestAlgorithm(otherCertId.OtherCertHash.HashAlgorithm.ObjectID.Id); otherCertId.OtherCertHash.GetHashValue(); certId.SetDigestValue(otherCertId.OtherCertHash.GetHashValue()); if (otherCertId.IssuerSerial != null) { if (otherCertId.IssuerSerial.Issuer != null) { certId.SetIssuerName(otherCertId.IssuerSerial.Issuer.ToString()); } if (otherCertId.IssuerSerial.Serial != null) { certId.SetIssuerSerial(otherCertId.IssuerSerial.Serial.ToString()); } } list.Add(certId); } } } return(list); }
public virtual IList <OCSPRef> GetOCSPRefs() { IList <OCSPRef> list = new List <OCSPRef>(); if (signerInformation.UnsignedAttributes != null) { BcCms.Attribute completeRevocationRefsAttr = signerInformation.UnsignedAttributes [PkcsObjectIdentifiers.IdAAEtsRevocationRefs]; if (completeRevocationRefsAttr != null && completeRevocationRefsAttr.AttrValues .Count > 0) { DerSequence completeRevocationRefs = (DerSequence)completeRevocationRefsAttr.AttrValues[0]; for (int i1 = 0; i1 < completeRevocationRefs.Count; i1++) { CrlOcspRef otherCertId = CrlOcspRef.GetInstance(completeRevocationRefs[i1]); foreach (OcspResponsesID id in otherCertId.OcspIDs.GetOcspResponses()) { list.Add(new OCSPRef(id, true)); } } } } return(list); }
public void Upgrade(SignatureDocument signatureDocument, SignerInfoNode signerInfoNode, UpgradeParameters parameters) { BcCms.AttributeTable unsigned = signerInfoNode.SignerInformation.UnsignedAttributes; IDictionary unsignedAttrHash = null; if (unsigned == null) { unsignedAttrHash = new Dictionary <DerObjectIdentifier, BcCms.Attribute>(); } else { unsignedAttrHash = signerInfoNode.SignerInformation.UnsignedAttributes.ToDictionary(); } BcCms.Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken , parameters.TsaClient, parameters.DigestMethod, signerInfoNode.SignerInformation.GetSignature()); unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(signerInfoNode.SignerInformation, new BcCms.AttributeTable(unsignedAttrHash)); signerInfoNode.SignerInformation = newsi; }
public void GetNuGetPackageOwners_WithMultipleAttributeValues_Throws() { using (var certificate = _fixture.GetDefaultCertificate()) { var attributes = CreateAttributeCollection(certificate, _fixture.DefaultKeyPair.Private, vector => { var value = new DerSequence( new DerUtf8String("a"), new DerUtf8String("b"), new DerUtf8String("c")); var attribute = new BcAttribute( new DerObjectIdentifier(Oids.NuGetPackageOwners), new DerSet(value, value)); vector.Add(attribute); }); var exception = Assert.Throws <SignatureException>( () => AttributeUtility.GetNuGetPackageOwners(attributes)); Assert.Equal("The nuget-package-owners attribute must have exactly one attribute value.", exception.Message); } }
private byte[] GetEContent() { SignerInfo signerInfo = GetSignerInfo(); Asn1Set signedAttributesSet = signerInfo.AuthenticatedAttributes; ContentInfo contentInfo = _signedData.EncapContentInfo; byte[] contentBytes = ((DerOctetString)contentInfo.Content).GetOctets(); if (signedAttributesSet.Count == 0) // signed attributes absent, return content to be signed return contentBytes; else // Signed attributes present (i.e. a structure containing a hash of the content), return that structure to be signed... // This option is taken by ICAO passports. { byte[] attributeBytes = signedAttributesSet.GetDerEncoded(); string digAlg = signerInfo.DigestAlgorithm.ObjectID.Id; // We'd better check that the content actually digests to the hash value contained! ;) IEnumerator attributes = signedAttributesSet.GetEnumerator(); byte[] storedDigestedContent = null; while (attributes.MoveNext()) { Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute((Asn1Sequence)attributes.Current); DerObjectIdentifier attrType = attribute.AttrType; if (attrType.Equals(RFC_3369_MESSAGE_DIGEST_OID)) { Asn1Set attrValueSet = attribute.AttrValues; if (attrValueSet.Count != 1) Console.WriteLine("WARNING: expected only one attribute value in signedAttribute message diegest in eContent!"); storedDigestedContent = ((DerOctetString)attrValueSet[0]).GetOctets(); } } if(storedDigestedContent == null) Console.WriteLine("WARNING: error extracting signedAttribute message digest in eContent!"); byte[] computedDigestedContent = SHA256.Create().ComputeHash(contentBytes); if (!Compare(storedDigestedContent, computedDigestedContent)) Console.WriteLine("WARNING: error checking signedAttribute message digest in eContent!"); return attributeBytes; } }
private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime? requestTimestamp = null) { var signCertAlias = signCertificate.Aliases.Cast<string>().First(signCertificate.IsKeyEntry); var signCertEntry = signCertificate.GetCertificate(signCertAlias); var signCert = signCertEntry.Certificate; var signPkEntry = signCertificate.GetKey(signCertAlias); var signPk = signPkEntry.Key; string digestName; if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id) { digestName = "SHA1"; } else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id) { digestName = "SHA256"; } else { throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}"); } var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id; var digest = DigestUtilities.CalculateDigest(digestName, data); var signedAttrs = new Dictionary<object, object>() { { CmsAttributeTableParameter.Digest, digest } }; if (requestTimestamp.HasValue) { var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime()))); signedAttrs.Add(signTimestamp.AttrType, signTimestamp); } var signedAttrGen = new DefaultSignedAttributeTableGenerator(); var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs); var generator = new CmsSignedDataGenerator(); generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null); var signedData = generator.Generate(new CmsProcessableByteArray(data), true); return signedData.GetEncoded(); }
/// <summary> /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the /// provided. /// </summary> /// <remarks> /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the /// provided. The hashing is performed by the method using the specified algorithm and a BouncyCastle provider. /// </remarks> /// <param name="signedData"></param> /// <exception cref="System.Exception">System.Exception</exception> protected internal virtual BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid , ITspSource tsa, AlgorithmIdentifier digestAlgorithm, byte[] messageImprint) { try { //jbonilla Hack para obtener el digest del TSA IDigest digest = null; string algorithmName = null; if (tsa is ITSAClient) { //TODO jbonilla - ¿AlgorithmIdentifier? digest = ((ITSAClient)tsa).GetMessageDigest(); algorithmName = digest.AlgorithmName; } else { digest = DigestUtilities.GetDigest(DigestAlgorithm.SHA1.GetName()); algorithmName = DigestAlgorithm.SHA1.GetName(); } byte[] toTimeStamp = DigestAlgorithms.Digest(digest, messageImprint); TimeStampResponse tsresp = tsa.GetTimeStampResponse(DigestAlgorithm.GetByName(algorithmName) , toTimeStamp); TimeStampToken tstoken = tsresp.TimeStampToken; if (tstoken == null) { throw new ArgumentNullException("The TimeStampToken returned for the signature time stamp was empty." ); } BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray (tstoken.GetEncoded()))); return signatureTimeStamp; } catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }