internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Expected O, but got Unknown AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID; string digestAlgName = Helper.GetDigestAlgName(digestOID); string algorithm = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID); byte[] array; if (outer._digests.Contains((object)digestOID)) { array = (byte[])outer._digests.get_Item((object)digestOID); } else { IDigest digestInstance = Helper.GetDigestInstance(digestAlgName); content?.Write((Stream)(object)new DigOutputStream(digestInstance)); array = DigestUtilities.DoFinal(digestInstance); outer._digests.Add((object)digestOID, ((global::System.Array)array).Clone()); } IStreamCalculator streamCalculator = sigCalc.CreateCalculator(); Stream val = (Stream) new BufferedStream(streamCalculator.Stream); Asn1Set asn1Set = null; if (sAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array); Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters); if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null) { IDictionary val2 = attributeTable.ToDictionary(); val2.Remove((object)CmsAttributes.ContentType); attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(val2); } asn1Set = outer.GetAttributeSet(attributeTable); new DerOutputStream(val).WriteObject(asn1Set); } else { content?.Write(val); } Platform.Dispose(val); byte[] array2 = ((IBlockResult)streamCalculator.GetResult()).Collect(); Asn1Set unauthenticatedAttributes = null; if (unsAttr != null) { IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array); baseParameters2.set_Item((object)CmsAttributeTableParameter.Signature, ((global::System.Array)array2).Clone()); Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2); unauthenticatedAttributes = outer.GetAttributeSet(attributes); } Asn1Encodable defaultX509Parameters = SignerUtilities.GetDefaultX509Parameters(algorithm); AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters); return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes)); }
internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID; string digestAlgName = Helper.GetDigestAlgName(digestOID); string algorithm = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID); byte[] array; if (outer._digests.Contains(digestOID)) { array = (byte[])outer._digests[digestOID]; } else { IDigest digestInstance = Helper.GetDigestInstance(digestAlgName); content?.Write(new DigOutputStream(digestInstance)); array = DigestUtilities.DoFinal(digestInstance); outer._digests.Add(digestOID, array.Clone()); } IStreamCalculator streamCalculator = sigCalc.CreateCalculator(); Stream stream = new BufferedStream(streamCalculator.Stream); Asn1Set asn1Set = null; if (sAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array); Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters); if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null) { IDictionary dictionary = attributeTable.ToDictionary(); dictionary.Remove(CmsAttributes.ContentType); attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary); } asn1Set = outer.GetAttributeSet(attributeTable); new DerOutputStream(stream).WriteObject(asn1Set); } else { content?.Write(stream); } Platform.Dispose(stream); byte[] array2 = ((IBlockResult)streamCalculator.GetResult()).Collect(); Asn1Set unauthenticatedAttributes = null; if (unsAttr != null) { IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array); baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone(); Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2); unauthenticatedAttributes = outer.GetAttributeSet(attributes); } Asn1Encodable defaultX509Parameters = SignerUtilities.GetDefaultX509Parameters(algorithm); AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters); return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes)); }
internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digestAlgorithmID = this.DigestAlgorithmID; string digestAlgName = CmsSignedDataGenerator.Helper.GetDigestAlgName(this.digestOID); IDigest digestInstance = CmsSignedDataGenerator.Helper.GetDigestInstance(digestAlgName); string algorithm = digestAlgName + "with" + CmsSignedDataGenerator.Helper.GetEncryptionAlgName(this.encOID); ISigner signatureInstance = CmsSignedDataGenerator.Helper.GetSignatureInstance(algorithm); if (content != null) { content.Write(new DigOutputStream(digestInstance)); } byte[] array = DigestUtilities.DoFinal(digestInstance); this.outer._digests.Add(this.digestOID, array.Clone()); signatureInstance.Init(true, new ParametersWithRandom(this.key, random)); Stream stream = new BufferedStream(new SigOutputStream(signatureInstance)); Asn1Set asn1Set = null; if (this.sAttr != null) { IDictionary baseParameters = this.outer.GetBaseParameters(contentType, digestAlgorithmID, array); Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = this.sAttr.GetAttributes(baseParameters); if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null) { IDictionary dictionary = attributeTable.ToDictionary(); dictionary.Remove(CmsAttributes.ContentType); attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary); } asn1Set = this.outer.GetAttributeSet(attributeTable); new DerOutputStream(stream).WriteObject(asn1Set); } else if (content != null) { content.Write(stream); } stream.Close(); byte[] array2 = signatureInstance.GenerateSignature(); Asn1Set unauthenticatedAttributes = null; if (this.unsAttr != null) { IDictionary baseParameters2 = this.outer.GetBaseParameters(contentType, digestAlgorithmID, array); baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone(); Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this.unsAttr.GetAttributes(baseParameters2); unauthenticatedAttributes = this.outer.GetAttributeSet(attributes); } Asn1Encodable defaultX509Parameters = SignerUtilities.GetDefaultX509Parameters(algorithm); AlgorithmIdentifier encAlgorithmIdentifier = CmsSignedGenerator.GetEncAlgorithmIdentifier(new DerObjectIdentifier(this.encOID), defaultX509Parameters); return(new SignerInfo(this.signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes)); }
internal void Generate(Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { Stream stream = Open(outStream, eContentType, encapsulate, dataOutputStream); content?.Write(stream); Platform.Dispose(stream); }
public CmsCompressedData Generate(CmsProcessable content, string compressionOid) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0037: Expected O, but got Unknown AlgorithmIdentifier compressionAlgorithm; Asn1OctetString content2; try { MemoryStream val = new MemoryStream(); ZOutputStream zOutputStream = new ZOutputStream((Stream)(object)val, -1); content.Write((Stream)(object)zOutputStream); Platform.Dispose((Stream)(object)zOutputStream); compressionAlgorithm = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); content2 = new BerOctetString(val.ToArray()); } catch (IOException val2) { IOException e = val2; throw new CmsException("exception encoding data.", (global::System.Exception)(object) e); } ContentInfo encapContentInfo = new ContentInfo(CmsObjectIdentifiers.Data, content2); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.CompressedData, new CompressedData(compressionAlgorithm, encapContentInfo)); return(new CmsCompressedData(contentInfo)); }
/** * Generate an object that contains an CMS Compressed Data */ public CmsCompressedData Generate( CmsProcessable content, string compressionOid) { AlgorithmIdentifier comAlgId; Asn1OctetString comOcts; try { MemoryStream bOut = new MemoryStream(); ZOutputStream zOut = new ZOutputStream(bOut, JZlib.Z_DEFAULT_COMPRESSION); content.Write(zOut); Platform.Dispose(zOut); comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); comOcts = new BerOctetString(bOut.ToArray()); } catch (IOException e) { throw new CmsException("exception encoding data.", e); } ContentInfo comContent = new ContentInfo(CmsObjectIdentifiers.Data, comOcts); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.CompressedData, new CompressedData(comAlgId, comContent)); return(new CmsCompressedData(contentInfo)); }
/** * Generate an object that contains an CMS Compressed Data */ public CmsCompressedData Generate( CmsProcessable content, string compressionOid) { AlgorithmIdentifier comAlgId; Asn1OctetString comOcts; try { MemoryStream bOut = new MemoryStream(); ZOutputStream zOut = new ZOutputStream(bOut, JZlib.Z_DEFAULT_COMPRESSION); content.Write(zOut); zOut.Dispose(); comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); comOcts = new BerOctetString(bOut.ToArray()); } catch (IOException e) { throw new CmsException("exception encoding data.", e); } ContentInfo comContent = new ContentInfo(CmsObjectIdentifiers.Data, comOcts); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.CompressedData, new CompressedData(comAlgId, comContent)); return new CmsCompressedData(contentInfo); }
private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { KeyParameter keyParameter; AlgorithmIdentifier algorithmIdentifier; Asn1OctetString content2; Asn1OctetString mac2; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array); algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out ICipherParameters _); IMac mac = MacUtilities.GetMac(macOid); mac.Init(keyParameter); MemoryStream memoryStream = new MemoryStream(); Stream stream = new TeeOutputStream(memoryStream, new MacOutputStream(mac)); content.Write(stream); Platform.Dispose(stream); content2 = new BerOctetString(memoryStream.ToArray()); byte[] str = MacUtilities.DoFinal(mac); mac2 = new DerOctetString(str); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e2) { throw new CmsException("key invalid in message.", e2); } catch (IOException e3) { throw new CmsException("exception decoding algorithm parameters.", e3); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators) { try { asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand)); } catch (InvalidKeyException e4) { throw new CmsException("key inappropriate for algorithm.", e4); } catch (GeneralSecurityException e5) { throw new CmsException("error making encrypted content.", e5); } } ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null)); return(new CmsAuthenticatedData(contentInfo)); }
internal void Generate(Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { Stream stream = this.Open(outStream, eContentType, encapsulate, dataOutputStream); if (content != null) { content.Write(stream); } stream.Close(); }
// TODO Make public? internal void Generate(Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { using (Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream)) { if (content != null) { content.Write(signedOut); } } }
public TimeStampToken( CmsSignedData signedData) { this.tsToken = signedData; if (!this.tsToken.SignedContentTypeOid.Equals(PkcsObjectIdentifiers.IdCTTstInfo.Id)) { 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 signerEnum = signers.GetEnumerator(); signerEnum.MoveNext(); tsaSignerInfo = (SignerInformation)signerEnum.Current; try { CmsProcessable content = tsToken.SignedContent; MemoryStream bOut = new MemoryStream(); content.Write(bOut); this.tstInfo = new TimeStampTokenInfo( TstInfo.GetInstance( Asn1Object.FromByteArray(bOut.ToArray()))); Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[ PkcsObjectIdentifiers.IdAASigningCertificate]; if (attr == null) { throw new TspValidationException( "no signing certificate attribute found, time stamp invalid."); } SigningCertificate signCert = SigningCertificate.GetInstance( attr.AttrValues[0]); this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]); } catch (CmsException e) { throw new TspException(e.Message, e.InnerException); } }
// TODO Make public? internal void Generate( Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream); if (content != null) { content.Write(signedOut); } BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(signedOut); }
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); } }
public TimeStampToken(CmsSignedData signedData) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown tsToken = signedData; if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo)) { throw new TspValidationException("ContentInfo object not for a time stamp."); } global::System.Collections.ICollection signers = tsToken.GetSignerInfos().GetSigners(); if (signers.get_Count() != 1) { throw new ArgumentException(string.Concat((object)"Time-stamp token signed by ", (object)signers.get_Count(), (object)" signers, but it must contain just the TSA signature.")); } global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)signers).GetEnumerator(); enumerator.MoveNext(); tsaSignerInfo = (SignerInformation)enumerator.get_Current(); try { CmsProcessable signedContent = tsToken.SignedContent; MemoryStream val = new MemoryStream(); signedContent.Write((Stream)(object)val); tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(val.ToArray()))); Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate]; if (attribute != null) { SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]); certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0])); return; } 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(((global::System.Exception)ex).get_Message(), ((global::System.Exception)ex).get_InnerException()); } }
// TODO Make public? internal void Generate( Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream); if (content != null) { content.Write(signedOut); } #if !NETFX_CORE signedOut.Close(); #else signedOut.Dispose(); #endif }
public CmsCompressedData Generate(CmsProcessable content, string compressionOid) { AlgorithmIdentifier compressionAlgorithm; Asn1OctetString content2; try { MemoryStream memoryStream = new MemoryStream(); ZOutputStream zOutputStream = new ZOutputStream(memoryStream, -1); content.Write(zOutputStream); Platform.Dispose(zOutputStream); compressionAlgorithm = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); content2 = new BerOctetString(memoryStream.ToArray()); } catch (IOException e) { throw new CmsException("exception encoding data.", e); } ContentInfo encapContentInfo = new ContentInfo(CmsObjectIdentifiers.Data, content2); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.CompressedData, new CompressedData(compressionAlgorithm, encapContentInfo)); return(new CmsCompressedData(contentInfo)); }
/** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CmsSignedData Generate( string signedContentType, // FIXME Avoid accessing more than once to support CmsProcessableInputStream CmsProcessable content, bool encapsulate) { Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); _digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. // foreach (SignerInformation signer in _signers) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); // TODO Verify the content type and calculated digest match the precalculated SignerInfo signerInfos.Add(signer.ToSignerInfo()); } // // add the SignerInfo objects // bool isCounterSignature = (signedContentType == null); DerObjectIdentifier contentTypeOid = isCounterSignature ? null : new DerObjectIdentifier(signedContentType); foreach (SignerInf signer in signerInfs) { try { digestAlgs.Add(signer.DigestAlgorithmID); signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for signature.", e); } catch (SignatureException e) { throw new CmsException("error creating signature.", e); } catch (CertificateEncodingException e) { throw new CmsException("error creating sid.", e); } } Asn1Set certificates = null; if (_certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set certrevlist = null; if (_crls.Count != 0) { certrevlist = CmsUtilities.CreateBerSetFromList(_crls); } Asn1OctetString octs = null; if (encapsulate) { MemoryStream bOut = new MemoryStream(); if (content != null) { try { content.Write(bOut); } catch (IOException e) { throw new CmsException("encapsulation error.", e); } } octs = new BerOctetString(bOut.ToArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOid, octs); SignedData sd = new SignedData( new DerSet(digestAlgs), encInfo, certificates, certrevlist, new DerSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd); return(new CmsSignedData(content, contentInfo)); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); byte[] hash; if (outer._digests.Contains(digestOID)) { hash = (byte[])outer._digests[digestOID]; } else { IDigest dig = Helper.GetDigestInstance(digestName); if (content != null) { content.Write(new DigOutputStream(dig)); } hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IStreamCalculator calculator = sigCalc.CreateCalculator(); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE Stream sigStr = calculator.Stream; #else Stream sigStr = new BufferedStream(calculator.Stream); #endif Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); AttributeTable signed = sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new AttributeTable(tmpSigned); } } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } Platform.Dispose(sigStr); byte[] sigBytes = ((IBlockResult)calculator.GetResult()).Collect(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = Helper.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
/** * generate an enveloped object that contains an CMS Enveloped Data * object using the given provider and the passed in key generator. */ private CmsAuthenticatedData Generate( CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier macAlgId; KeyParameter encKey; Asn1OctetString encContent; Asn1OctetString macResult; try { // FIXME Will this work for macs? byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes); ICipherParameters cipherParameters; macAlgId = GetAlgorithmIdentifier( macOid, encKey, asn1Params, out cipherParameters); IMac mac = MacUtilities.GetMac(macOid); // TODO Confirm no ParametersWithRandom needed // FIXME Only passing key at the moment // mac.Init(cipherParameters); mac.Init(encKey); MemoryStream bOut = new MemoryStream(); Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac)); content.Write(mOut); mOut.Close(); bOut.Close(); encContent = new BerOctetString(bOut.ToArray()); byte[] macOctets = MacUtilities.DoFinal(mac); macResult = new DerOctetString(macOctets); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null)); return new CmsAuthenticatedData(contentInfo); }
public CmsSignedData Generate(string signedContentType, CmsProcessable content, bool encapsulate) { //IL_0113: Expected O, but got Unknown //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Expected O, but got Unknown //IL_01c6: Expected O, but got Unknown Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(); _digests.Clear(); global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)_signers).GetEnumerator(); try { while (enumerator.MoveNext()) { SignerInformation signerInformation = (SignerInformation)enumerator.get_Current(); asn1EncodableVector.Add(Helper.FixAlgID(signerInformation.DigestAlgorithmID)); asn1EncodableVector2.Add(signerInformation.ToSignerInfo()); } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } DerObjectIdentifier contentType = ((signedContentType == null) ? null : new DerObjectIdentifier(signedContentType)); enumerator = ((global::System.Collections.IEnumerable)signerInfs).GetEnumerator(); try { while (enumerator.MoveNext()) { SignerInf signerInf = (SignerInf)enumerator.get_Current(); try { asn1EncodableVector.Add(signerInf.DigestAlgorithmID); asn1EncodableVector2.Add(signerInf.ToSignerInfo(contentType, content, rand)); } catch (IOException val) { IOException e = val; throw new CmsException("encoding error.", (global::System.Exception)(object) e); } catch (InvalidKeyException e2) { throw new CmsException("key inappropriate for signature.", e2); } catch (SignatureException e3) { throw new CmsException("error creating signature.", e3); } catch (CertificateEncodingException e4) { throw new CmsException("error creating sid.", e4); } } } finally { global::System.IDisposable disposable2 = enumerator as global::System.IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } Asn1Set certificates = null; if (((global::System.Collections.ICollection)_certs).get_Count() != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set crls = null; if (((global::System.Collections.ICollection)_crls).get_Count() != 0) { crls = CmsUtilities.CreateBerSetFromList(_crls); } Asn1OctetString content2 = null; if (encapsulate) { MemoryStream val2 = new MemoryStream(); if (content != null) { try { content.Write((Stream)(object)val2); } catch (IOException val3) { IOException e5 = val3; throw new CmsException("encapsulation error.", (global::System.Exception)(object) e5); } } content2 = new BerOctetString(val2.ToArray()); } ContentInfo contentInfo = new ContentInfo(contentType, content2); SignedData content3 = new SignedData(new DerSet(asn1EncodableVector), contentInfo, certificates, crls, new DerSet(asn1EncodableVector2)); ContentInfo sigData = new ContentInfo(CmsObjectIdentifiers.SignedData, content3); return(new CmsSignedData(content, sigData)); }
internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(_digestOID); IDigest dig = Helper.GetDigestInstance(digestName); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(_encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); // TODO Optimise the case where more than one signer with same digest if (content != null) { content.Write(new DigOutputStream(dig)); } byte[] hash = DigestUtilities.DoFinal(dig); _outer._digests.Add(_digestOID, hash.Clone()); sig.Init(true, new ParametersWithRandom(_key, random)); Asn1Set signedAttr = null; using (Stream sigStr = new SigOutputStream(sig)) { if (_sAttr != null) { IDictionary parameters = _outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } } // TODO Validate proposed signed attributes signedAttr = _outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } } byte[] sigBytes = sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (_unsAttr != null) { IDictionary baseParameters = _outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = _outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = GetEncAlgorithmIdentifier(new DerObjectIdentifier(_encOID), sigX509Parameters); return(new SignerInfo(_signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
internal Asn1.Cms.SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random, bool isCounterSignature) { AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid); string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); IDigest dig = Helper.GetDigestInstance(digestName); byte[] hash = null; if (content != null) { content.Write(new DigOutputStream(dig)); hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); Asn1.Cms.AttributeTable signed = (sAttr != null) // ? sAttr.GetAttributes(Collections.unmodifiableMap(parameters)) ? sAttr.GetAttributes(parameters) : null; if (isCounterSignature) { Hashtable ats = signed.ToHashtable(); ats.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(ats); } Asn1Set signedAttr = outer.GetAttributeSet(signed); // // sig must be composed from the DER encoding. // byte[] tmp; if (signedAttr != null) { tmp = signedAttr.GetEncoded(Asn1Encodable.Der); } else { MemoryStream bOut = new MemoryStream(); content.Write(bOut); tmp = bOut.ToArray(); } sig.Init(true, new ParametersWithRandom(key, random)); sig.BlockUpdate(tmp, 0, tmp.Length); Asn1OctetString encDigest = new DerOctetString(sig.GenerateSignature()); IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone(); Asn1.Cms.AttributeTable unsigned = (unsAttr != null) // ? unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)) ? unsAttr.GetAttributes(baseParameters) : null; Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned); X509Certificate cert = this.GetCertificate(); SignerIdentifier identifier; if (cert != null) { TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); identifier = new SignerIdentifier(encSid); } else { identifier = new SignerIdentifier(new DerOctetString(keyIdentifier)); } return(new Asn1.Cms.SignerInfo(identifier, digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr)); }
private bool DoVerify( AsymmetricKeyParameter key) { string digestName = Helper.GetDigestAlgName(this.DigestAlgOid); IDigest digest = Helper.GetDigestInstance(digestName); DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID; Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters; ISigner sig; if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss)) { // RFC 4056 2.2 // When the id-RSASSA-PSS algorithm identifier is used for a signature, // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. if (sigParams == null) { throw new CmsException("RSASSA-PSS signature must specify algorithm parameters"); } try { // TODO Provide abstract configuration mechanism // (via alternate SignerUtilities.GetSigner method taking ASN.1 params) Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance( sigParams.ToAsn1Object()); if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID)) { throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm"); } if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1)) { throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF"); } IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID); int saltLength = pss.SaltLength.Value.IntValue; byte trailerField = (byte)pss.TrailerField.Value.IntValue; // RFC 4055 3.1 // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC if (trailerField != 1) { throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1"); } sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength); } catch (Exception e) { throw new CmsException("failed to set RSASSA-PSS signature parameters", e); } } else { // TODO Probably too strong a check at the moment // if (sigParams != null) // throw new CmsException("unrecognised signature parameters provided"); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid); sig = Helper.GetSignatureInstance(signatureName); } try { if (digestCalculator != null) { resultDigest = digestCalculator.GetDigest(); } else { if (content != null) { content.Write(new DigOutputStream(digest)); } else if (signedAttributeSet == null) { // TODO Get rid of this exception and just treat content==null as empty not missing? throw new CmsException("data not encapsulated in signature - use detached constructor."); } resultDigest = DigestUtilities.DoFinal(digest); } } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } // RFC 3852 11.1 Check the content-type attribute is correct { Asn1Object validContentType = GetSingleValuedSignedAttribute( CmsAttributes.ContentType, "content-type"); if (validContentType == null) { if (!isCounterSignature && signedAttributeSet != null) { throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); } } else { if (isCounterSignature) { throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); } if (!(validContentType is DerObjectIdentifier)) { throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'"); } DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType; if (!signedContentType.Equals(contentType)) { throw new CmsException("content-type attribute value does not match eContentType"); } } } // RFC 3852 11.2 Check the message-digest attribute is correct { Asn1Object validMessageDigest = GetSingleValuedSignedAttribute( CmsAttributes.MessageDigest, "message-digest"); if (validMessageDigest == null) { if (signedAttributeSet != null) { throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present"); } } else { if (!(validMessageDigest is Asn1OctetString)) { throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'"); } Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest; if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets())) { throw new CmsException("message-digest attribute value does not match calculated value"); } } } // RFC 3852 11.4 Validate countersignature attribute(s) { Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes; if (signedAttrTable != null && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0) { throw new CmsException("A countersignature attribute MUST NOT be a signed attribute"); } Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes; if (unsignedAttrTable != null) { foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature)) { if (csAttr.AttrValues.Count < 1) { throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue"); } // Note: We don't recursively validate the countersignature value } } } try { sig.Init(false, key); if (signedAttributeSet == null) { if (digestCalculator != null) { // need to decrypt signature and check message bytes return(VerifyDigest(resultDigest, key, this.GetSignature())); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(new SigOutputStream(sig)); } } else { byte[] tmp = this.GetEncodedSignedAttributes(); sig.BlockUpdate(tmp, 0, tmp.Length); } return(sig.VerifySignature(this.GetSignature())); } catch (InvalidKeyException e) { throw new CmsException("key not appropriate to signature in message.", e); } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } catch (SignatureException e) { throw new CmsException("invalid signature format in message: " + e.Message, e); } }
/** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CmsSignedData Generate( string signedContentType, // FIXME Avoid accessing more than once to support CmsProcessableInputStream CmsProcessable content, bool encapsulate) { Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); _digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. // foreach (SignerInformation signer in _signers) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); // TODO Verify the content type and calculated digest match the precalculated SignerInfo signerInfos.Add(signer.ToSignerInfo()); } // // add the SignerInfo objects // bool isCounterSignature = (signedContentType == null); DerObjectIdentifier contentTypeOid = isCounterSignature ? null : new DerObjectIdentifier(signedContentType); foreach (SignerInf signer in signerInfs) { try { digestAlgs.Add(signer.DigestAlgorithmID); signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for signature.", e); } catch (SignatureException e) { throw new CmsException("error creating signature.", e); } catch (CertificateEncodingException e) { throw new CmsException("error creating sid.", e); } } Asn1Set certificates = null; if (_certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set certrevlist = null; if (_crls.Count != 0) { certrevlist = CmsUtilities.CreateBerSetFromList(_crls); } Asn1OctetString octs = null; if (encapsulate) { MemoryStream bOut = new MemoryStream(); if (content != null) { try { content.Write(bOut); } catch (IOException e) { throw new CmsException("encapsulation error.", e); } } octs = new BerOctetString(bOut.ToArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOid, octs); SignedData sd = new SignedData( new DerSet(digestAlgs), encInfo, certificates, certrevlist, new DerSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd); return new CmsSignedData(content, contentInfo); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); IDigest dig = Helper.GetDigestInstance(digestName); //jbonilla string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = outer._signerProvider != null ? outer._signerProvider : Helper.GetSignatureInstance(signatureName); byte[] hash = null; byte[] preCalculatedHash = ((CustomCMSSignedDataGenerator)outer).PreCalculatedDigest; if (preCalculatedHash != null) { hash = preCalculatedHash; } else if (content != null) { content.Write(new DigOutputStream(dig)); hash = DigestUtilities.DoFinal(dig); } outer._digests.Add(digestOID, hash.Clone()); sig.Init(true, new ParametersWithRandom(key, random)); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT Stream sigStr = new SigOutputStream(sig); #else Stream sigStr = new BufferedStream(new SigOutputStream(sig)); #endif Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); //Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Org.BouncyCastle.Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Org.BouncyCastle.Asn1.Cms.AttributeTable(tmpSigned); } } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } sigStr.Close(); byte[] sigBytes = sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
public CmsEnvelopedData Generate(CmsProcessable content, ICipherBuilderWithKey cipherBuilder) { //AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { encKey = (KeyParameter)cipherBuilder.Key; MemoryStream collector = new MemoryStream(); Stream bOut = cipherBuilder.BuildCipher(collector).Stream; content.Write(bOut); Platform.Dispose(bOut); encContent = new BerOctetString(collector.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } EncryptedContentInfo eci = new EncryptedContentInfo( CmsObjectIdentifiers.Data, (AlgorithmIdentifier)cipherBuilder.AlgorithmDetails, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return(new CmsEnvelopedData(contentInfo)); }
private bool DoVerify( AsymmetricKeyParameter key, Asn1.Cms.AttributeTable signedAttrTable) { string digestName = Helper.GetDigestAlgName(this.DigestAlgOid); IDigest digest = Helper.GetDigestInstance(digestName); DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID; Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters; ISigner sig; if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss)) { // RFC 4056 2.2 // When the id-RSASSA-PSS algorithm identifier is used for a signature, // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. if (sigParams == null) { throw new CmsException("RSASSA-PSS signature must specify algorithm parameters"); } try { // TODO Provide abstract configuration mechanism Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance( sigParams.ToAsn1Object()); if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID)) { throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm"); } if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1)) { throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF"); } IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID); int saltLength = pss.SaltLength.Value.IntValue; byte trailerField = (byte)pss.TrailerField.Value.IntValue; // RFC 4055 3.1 // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC if (trailerField != 1) { throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1"); } sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength); } catch (Exception e) { throw new CmsException("failed to set RSASSA-PSS signature parameters", e); } } else { // TODO Probably too strong a check at the moment // if (sigParams != null) // throw new CmsException("unrecognised signature parameters provided"); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid); sig = Helper.GetSignatureInstance(signatureName); } try { sig.Init(false, key); if (signedAttributes == null) { if (content != null) { content.Write(new CmsSignedDataGenerator.SigOutputStream(sig)); content.Write(new CmsSignedDataGenerator.DigOutputStream(digest)); resultDigest = DigestUtilities.DoFinal(digest); } else { resultDigest = digestCalculator.GetDigest(); // need to decrypt signature and check message bytes return(VerifyDigest(resultDigest, key, this.GetSignature())); } } else { byte[] hash; if (content != null) { content.Write( new CmsSignedDataGenerator.DigOutputStream(digest)); hash = DigestUtilities.DoFinal(digest); } else if (digestCalculator != null) { hash = digestCalculator.GetDigest(); } else { hash = null; } resultDigest = hash; Asn1.Cms.Attribute dig = signedAttrTable[Asn1.Cms.CmsAttributes.MessageDigest]; Asn1.Cms.Attribute type = signedAttrTable[Asn1.Cms.CmsAttributes.ContentType]; if (dig == null) { throw new SignatureException("no hash for content found in signed attributes"); } if (type == null && !contentType.Equals(CmsAttributes.CounterSignature)) { throw new SignatureException("no content type id found in signed attributes"); } Asn1Object hashObj = dig.AttrValues[0].ToAsn1Object(); if (hashObj is Asn1OctetString) { byte[] signedHash = ((Asn1OctetString)hashObj).GetOctets(); if (!Arrays.AreEqual(hash, signedHash)) { throw new SignatureException("content hash found in signed attributes different"); } } else if (hashObj is DerNull) { if (hash != null) { throw new SignatureException("NULL hash found in signed attributes when one expected"); } } if (type != null) { DerObjectIdentifier typeOID = (DerObjectIdentifier)type.AttrValues[0]; if (!typeOID.Equals(contentType)) { throw new SignatureException("contentType in signed attributes different"); } } byte[] tmp = this.GetEncodedSignedAttributes(); sig.BlockUpdate(tmp, 0, tmp.Length); } return(sig.VerifySignature(this.GetSignature())); } catch (InvalidKeyException e) { throw new CmsException( "key not appropriate to signature in message.", e); } catch (IOException e) { throw new CmsException( "can't process mime object to create signature.", e); } catch (SignatureException e) { throw new CmsException( "invalid signature format in message: " + e.Message, e); } }
/// <summary> /// Generate an enveloped object that contains a CMS Enveloped Data /// object using the passed in key generator. /// </summary> private CmsEnvelopedData Generate( CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes); ICipherParameters cipherParameters; encAlgId = GetAlgorithmIdentifier( encryptionOid, encKey, asn1Params, out cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); content.Write(cOut); cOut.Dispose(); encContent = new BerOctetString(bOut.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } EncryptedContentInfo eci = new EncryptedContentInfo( CmsObjectIdentifiers.Data, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return new CmsEnvelopedData(contentInfo); }
/** * generate an enveloped object that contains an CMS Enveloped Data * object using the given provider and the passed in key generator. */ private CmsAuthenticatedData Generate( CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier macAlgId; KeyParameter encKey; Asn1OctetString encContent; Asn1OctetString macResult; try { // FIXME Will this work for macs? byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes); ICipherParameters cipherParameters; macAlgId = GetAlgorithmIdentifier( macOid, encKey, asn1Params, out cipherParameters); IMac mac = MacUtilities.GetMac(macOid); // TODO Confirm no ParametersWithRandom needed // FIXME Only passing key at the moment // mac.Init(cipherParameters); mac.Init(encKey); MemoryStream bOut = new MemoryStream(); Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac)); content.Write(mOut); mOut.Close(); bOut.Close(); encContent = new BerOctetString(bOut.ToArray()); byte[] macOctets = MacUtilities.DoFinal(mac); macResult = new DerOctetString(macOctets); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null)); return(new CmsAuthenticatedData(contentInfo)); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random, bool isCounterSignature) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); IDigest dig = Helper.GetDigestInstance(digestName); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); // TODO Optimise the case where more than one signer with same digest if (content != null) { content.Write(new DigOutputStream(dig)); } byte[] hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); Asn1Set signedAttr = null; byte[] tmp; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (isCounterSignature) { Hashtable tmpSigned = signed.ToHashtable(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. tmp = signedAttr.GetEncoded(Asn1Encodable.Der); } else { // TODO Use raw signature of the hash value instead MemoryStream bOut = new MemoryStream(); if (content != null) { content.Write(bOut); } tmp = bOut.ToArray(); } sig.Init(true, new ParametersWithRandom(key, random)); sig.BlockUpdate(tmp, 0, tmp.Length); byte[] sigBytes = sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
private CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier algorithmIdentifier = null; KeyParameter keyParameter; Asn1OctetString encryptedContent; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, array); algorithmIdentifier = GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out ICipherParameters cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(forEncryption: true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream memoryStream = new MemoryStream(); CipherStream cipherStream = new CipherStream(memoryStream, null, cipher); content.Write(cipherStream); Platform.Dispose(cipherStream); encryptedContent = new BerOctetString(memoryStream.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e2) { throw new CmsException("key invalid in message.", e2); } catch (IOException e3) { throw new CmsException("exception decoding algorithm parameters.", e3); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators) { try { asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand)); } catch (InvalidKeyException e4) { throw new CmsException("key inappropriate for algorithm.", e4); } catch (GeneralSecurityException e5) { throw new CmsException("error making encrypted content.", e5); } } EncryptedContentInfo encryptedContentInfo = new EncryptedContentInfo(CmsObjectIdentifiers.Data, algorithmIdentifier, encryptedContent); Asn1Set unprotectedAttrs = null; if (unprotectedAttributeGenerator != null) { Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrs = new BerSet(attributes.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(asn1EncodableVector), encryptedContentInfo, unprotectedAttrs)); return(new CmsEnvelopedData(contentInfo)); }
// TODO Make public? internal void Generate( Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream); if (content != null) { content.Write(signedOut); } signedOut.Close(); }
/** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CmsSignedData Generate( string signedContentType, CmsProcessable content, bool encapsulate) { Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); _digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. // foreach (SignerInformation signer in _signers) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); signerInfos.Add(signer.ToSignerInfo()); } // // add the SignerInfo objects // DerObjectIdentifier contentTypeOID; bool isCounterSignature; if (signedContentType != null) { contentTypeOID = new DerObjectIdentifier(signedContentType); isCounterSignature = false; } else { contentTypeOID = CmsObjectIdentifiers.Data; isCounterSignature = true; } foreach (SignerInf signer in signerInfs) { try { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); signerInfos.Add(signer.ToSignerInfo(contentTypeOID, content, rand, isCounterSignature)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for signature.", e); } catch (SignatureException e) { throw new CmsException("error creating signature.", e); } catch (CertificateEncodingException e) { throw new CmsException("error creating sid.", e); } } Asn1Set certificates = null; if (_certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set certrevlist = null; if (_crls.Count != 0) { certrevlist = CmsUtilities.CreateBerSetFromList(_crls); } Asn1OctetString octs = null; if (encapsulate) { MemoryStream bOut = new MemoryStream(); try { content.Write(bOut); } catch (IOException e) { throw new CmsException("encapsulation error.", e); } octs = new BerOctetString(bOut.ToArray()); } Asn1.Cms.ContentInfo encInfo = new Asn1.Cms.ContentInfo(contentTypeOID, octs); Asn1.Cms.SignedData sd = new Asn1.Cms.SignedData( new DerSet(digestAlgs), encInfo, certificates, certrevlist, new DerSet(signerInfos)); Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo( PkcsObjectIdentifiers.SignedData, sd); return new CmsSignedData(content, contentInfo); }
/// <summary> /// Generate an enveloped object that contains a CMS Enveloped Data /// object using the passed in key generator. /// </summary> private CmsEnvelopedData Generate( CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes); ICipherParameters cipherParameters; encAlgId = GetAlgorithmIdentifier( encryptionOid, encKey, asn1Params, out cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); content.Write(cOut); Platform.Dispose(cOut); encContent = new BerOctetString(bOut.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } EncryptedContentInfo eci = new EncryptedContentInfo( CmsObjectIdentifiers.Data, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return(new CmsEnvelopedData(contentInfo)); }
private CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_0096: Expected O, but got Unknown AlgorithmIdentifier algorithmIdentifier = null; KeyParameter keyParameter; Asn1OctetString encryptedContent; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, array); algorithmIdentifier = GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out var cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(forEncryption: true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream val = new MemoryStream(); CipherStream cipherStream = new CipherStream((Stream)(object)val, null, cipher); content.Write((Stream)(object)cipherStream); Platform.Dispose((Stream)(object)cipherStream); encryptedContent = new BerOctetString(val.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e2) { throw new CmsException("key invalid in message.", e2); } catch (IOException val2) { IOException e3 = val2; throw new CmsException("exception decoding algorithm parameters.", (global::System.Exception)(object) e3); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientInfoGenerators).GetEnumerator(); try { while (enumerator.MoveNext()) { RecipientInfoGenerator recipientInfoGenerator = (RecipientInfoGenerator)enumerator.get_Current(); try { asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand)); } catch (InvalidKeyException e4) { throw new CmsException("key inappropriate for algorithm.", e4); } catch (GeneralSecurityException e5) { throw new CmsException("error making encrypted content.", e5); } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } EncryptedContentInfo encryptedContentInfo = new EncryptedContentInfo(CmsObjectIdentifiers.Data, algorithmIdentifier, encryptedContent); Asn1Set unprotectedAttrs = null; if (unprotectedAttributeGenerator != null) { Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrs = new BerSet(attributes.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(asn1EncodableVector), encryptedContentInfo, unprotectedAttrs)); return(new CmsEnvelopedData(contentInfo)); }
/** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CmsSignedData Generate( string signedContentType, CmsProcessable content, bool encapsulate) { Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); _digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. // foreach (SignerInformation signer in _signers) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); signerInfos.Add(signer.ToSignerInfo()); } // // add the SignerInfo objects // DerObjectIdentifier contentTypeOID; bool isCounterSignature; if (signedContentType != null) { contentTypeOID = new DerObjectIdentifier(signedContentType); isCounterSignature = false; } else { contentTypeOID = CmsObjectIdentifiers.Data; isCounterSignature = true; } foreach (SignerInf signer in signerInfs) { try { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); signerInfos.Add(signer.ToSignerInfo(contentTypeOID, content, rand, isCounterSignature)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for signature.", e); } catch (SignatureException e) { throw new CmsException("error creating signature.", e); } catch (CertificateEncodingException e) { throw new CmsException("error creating sid.", e); } } Asn1Set certificates = null; if (_certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set certrevlist = null; if (_crls.Count != 0) { certrevlist = CmsUtilities.CreateBerSetFromList(_crls); } Asn1OctetString octs = null; if (encapsulate) { MemoryStream bOut = new MemoryStream(); try { content.Write(bOut); } catch (IOException e) { throw new CmsException("encapsulation error.", e); } octs = new BerOctetString(bOut.ToArray()); } Asn1.Cms.ContentInfo encInfo = new Asn1.Cms.ContentInfo(contentTypeOID, octs); Asn1.Cms.SignedData sd = new Asn1.Cms.SignedData( new DerSet(digestAlgs), encInfo, certificates, certrevlist, new DerSet(signerInfos)); Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo( PkcsObjectIdentifiers.SignedData, sd); return(new CmsSignedData(content, contentInfo)); }
/// <summary> /// Generate an enveloped object that contains a CMS Enveloped Data /// object using the passed in key generator. /// </summary> private CmsEnvelopedData Generate( CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = null; try { if (encryptionOid.Equals(RC2Cbc)) { // mix in a bit extra... rand.SetSeed(DateTime.Now.Ticks); byte[] iv = rand.GenerateSeed(8); // TODO Is this detailed repeat of Java version really necessary? int effKeyBits = encKeyBytes.Length * 8; int parameterVersion; if (effKeyBits < 256) { parameterVersion = rc2Table[effKeyBits]; } else { parameterVersion = effKeyBits; } asn1Params = new RC2CbcParameter(parameterVersion, iv); } else { asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand); } } catch (SecurityUtilityException) { // No problem... no parameters generated } Asn1Object asn1Object; ICipherParameters cipherParameters; if (asn1Params != null) { asn1Object = asn1Params.ToAsn1Object(); cipherParameters = ParameterUtilities.GetCipherParameters( encryptionOid, encKey, asn1Object); } else { asn1Object = DerNull.Instance; cipherParameters = encKey; } encAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(encryptionOid), asn1Object); cipher.Init(true, cipherParameters); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); content.Write(cOut); cOut.Close(); encContent = new BerOctetString(bOut.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInf recipient in recipientInfs) { try { recipientInfos.Add(recipient.ToRecipientInfo(encKey)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } EncryptedContentInfo eci = new EncryptedContentInfo( PkcsObjectIdentifiers.Data, encAlgId, encContent); Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo( PkcsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, null)); return new CmsEnvelopedData(contentInfo); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); byte[] hash; if (outer._digests.Contains(digestOID)) { hash = (byte[])outer._digests[digestOID]; } else { IDigest dig = Helper.GetDigestInstance(digestName); if (content != null) { content.Write(new DigOutputStream(dig)); } hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } sig.Init(true, new ParametersWithRandom(key, random)); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT Stream sigStr = new SigOutputStream(sig); #else Stream sigStr = new BufferedStream(new SigOutputStream(sig)); #endif Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } sigStr.Close(); byte[] sigBytes = sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr); }
internal Asn1.Cms.SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random, bool isCounterSignature) { AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid); string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); IDigest dig = Helper.GetDigestInstance(digestName); byte[] hash = null; if (content != null) { content.Write(new DigOutputStream(dig)); hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); Asn1.Cms.AttributeTable signed = (sAttr != null) // ? sAttr.GetAttributes(Collections.unmodifiableMap(parameters)) ? sAttr.GetAttributes(parameters) : null; if (isCounterSignature) { Hashtable ats = signed.ToHashtable(); ats.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(ats); } Asn1Set signedAttr = outer.GetAttributeSet(signed); // // sig must be composed from the DER encoding. // byte[] tmp; if (signedAttr != null) { tmp = signedAttr.GetEncoded(Asn1Encodable.Der); } else { MemoryStream bOut = new MemoryStream(); content.Write(bOut); tmp = bOut.ToArray(); } sig.Init(true, new ParametersWithRandom(key, random)); sig.BlockUpdate(tmp, 0, tmp.Length); Asn1OctetString encDigest = new DerOctetString(sig.GenerateSignature()); IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone(); Asn1.Cms.AttributeTable unsigned = (unsAttr != null) // ? unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)) ? unsAttr.GetAttributes(baseParameters) : null; Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned); X509Certificate cert = this.GetCertificate(); SignerIdentifier identifier; if (cert != null) { TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); identifier = new SignerIdentifier(encSid); } else { identifier = new SignerIdentifier(new DerOctetString(keyIdentifier)); } return new Asn1.Cms.SignerInfo(identifier, digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr); }