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)); }
/// <summary> /// RFC 3852의 EnvelopedData 구조체 중 KeyTransRecipientInfo 항목을 생성하고 /// 이를 이용해 RecipientInfo 구조체를 생성한다. /// </summary> /// <param name="x509_certificate2">키를 암호화하기 위한 공인인증서(국세청 공인인증서)</param> /// <param name="random_key">암호화에 사용된 램덤 키</param> /// <returns></returns> private RecipientInfo GetKeyTransRecipientInfo(X509Certificate2 x509_certificate2, byte[] random_key) { // RecipientIdentifier 필드에는 누구의 공개키를 이용하였는지에 대한 정보가 들어간다. // IssuerAndSerialNumber(ASN.1 형태) 데이터를 생성하기 위하여 파라미터로 전달받은 cert 를 Org.BouncyCastle.X509.X509Certificate 타입으로 변환한다. X509CertificateParser _x509Parser = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate _bouncyCert = _x509Parser.ReadCertificate(x509_certificate2.GetRawCertData()); // IssuerAndSerialNumber 데이터를 생성한다. Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber _issuerAndSerial = new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(_bouncyCert.IssuerDN, new DerInteger(_bouncyCert.SerialNumber)); // IssuerAndSerialNumber 데이터를 이용하여 RecipientIdentifier 형태의 데이터를 생성한다. RecipientIdentifier _rid = new RecipientIdentifier(_issuerAndSerial.ToAsn1Object()); // 대칭키 알고리즘에 사용된 키를 암호화할 때 이용되는 암호화 알고리즘에 대한 OID // 암호화 알고리즘 : RSA (비대칭 알고리즘) // OID : 1.2.840.113549.1.1.1 AlgorithmIdentifier _keyEncryptionAlgorithm = new AlgorithmIdentifier(new DerObjectIdentifier("1.2.840.113549.1.1.1")); // 랜덤키를 공개키를 사용해 암호화 한다. RSACryptoServiceProvider _rsaCrypto = (RSACryptoServiceProvider)x509_certificate2.PublicKey.Key; byte[] _byteEncryptedKey = _rsaCrypto.Encrypt(random_key, false); // 대칭키를 암호화 Asn1OctetString _encryptedKey = new BerOctetString(_byteEncryptedKey); // KeyTransRecipientInfo 구조체를 생성, 설정한다. KeyTransRecipientInfo _keyTransRecipientInfo = new KeyTransRecipientInfo(_rid, _keyEncryptionAlgorithm, _encryptedKey); // KeyTransRecipientInfo 구조체를 이용하여 RecipientInfo를 생성 및 설정한다. return(new RecipientInfo(_keyTransRecipientInfo)); }
/** * 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(); //DeflaterOutputStream zOut = null; //content.Write(zOut); //zOut.Close(); comAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(compressionOid), null); 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 CmsEnvelopedData doGenerate( ICmsTypedData content, ICipherBuilderWithKey<AlgorithmIdentifier> contentEncryptor) { Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); AlgorithmIdentifier encAlgId; Asn1OctetString encContent; MemoryOutputStream bOut = new MemoryOutputStream(); try { ICipher cOut = contentEncryptor.BuildCipher(bOut); content.Write(cOut.Stream); cOut.Stream.Close(); } catch (IOException e) { throw new CmsException(e.Message, e); } byte[] encryptedContent = bOut.ToArray(); encAlgId = contentEncryptor.AlgorithmDetails; encContent = new BerOctetString(encryptedContent); ISymmetricKey encKey = contentEncryptor.Key; for (IEnumerator<IRecipientInfoGenerator> it = recipientInfoGenerators.GetEnumerator(); it.MoveNext();) { IRecipientInfoGenerator recipient = (IRecipientInfoGenerator)it.Current; recipientInfos.Add(recipient.Generate(encKey)); } EncryptedContentInfo eci = new EncryptedContentInfo( content.ContentType, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary<string, object>()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(originatorInfo, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return new CmsEnvelopedData(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)); }
public static Asn1OctetString GetInstance(Asn1TaggedObject obj, bool isExplicit) { Asn1Object @object = obj.GetObject(); if (isExplicit || @object is Asn1OctetString) { return(GetInstance(@object)); } return(BerOctetString.FromSequence(Asn1Sequence.GetInstance(@object))); }
internal override void Encode(DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteTag(160, tagNo); derOut.WriteByte(128); if (!IsEmpty()) { if (!explicitly) { IEnumerable enumerable; if (base.obj is Asn1OctetString) { if (base.obj is BerOctetString) { enumerable = (BerOctetString)base.obj; } else { Asn1OctetString asn1OctetString = (Asn1OctetString)base.obj; enumerable = new BerOctetString(asn1OctetString.GetOctets()); } } else if (base.obj is Asn1Sequence) { enumerable = (Asn1Sequence)base.obj; } else { if (!(base.obj is Asn1Set)) { throw Platform.CreateNotImplementedException(Platform.GetTypeName(base.obj)); } enumerable = (Asn1Set)base.obj; } foreach (Asn1Encodable item in enumerable) { derOut.WriteObject(item); } } else { derOut.WriteObject(obj); } } derOut.WriteByte(0); derOut.WriteByte(0); } else { base.Encode(derOut); } }
private CmsEncryptedData doGenerate( ICmsTypedData content, ICipherBuilder <AlgorithmIdentifier> contentEncryptor) { AlgorithmIdentifier encAlgId; Asn1OctetString encContent; MemoryOutputStream bOut = new MemoryOutputStream(); try { ICipher cipher = contentEncryptor.BuildCipher(bOut); content.Write(cipher.Stream); cipher.Stream.Close(); } catch (IOException) { throw new CmsException(""); } byte[] encryptedContent = bOut.ToArray(); encAlgId = contentEncryptor.AlgorithmDetails; encContent = new BerOctetString(encryptedContent); EncryptedContentInfo eci = new EncryptedContentInfo( content.ContentType, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary <string, object>()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EncryptedData, new EncryptedData(eci, unprotectedAttrSet)); return(new CmsEncryptedData(contentInfo)); }
private byte[] GenerateTSRFile(byte[] originalContent, string fileName, byte[] timestampResponse) { DerIA5String derIA5String = null; if (!string.IsNullOrEmpty(fileName)) { derIA5String = new DerIA5String(fileName); } BerOctetString berOctetStrings = new BerOctetString(originalContent); TimeStampResponse timeStampResponse = new TimeStampResponse(timestampResponse); TimeStampAndCrl timeStampAndCrl = new TimeStampAndCrl(timeStampResponse.TimeStampToken.ToCmsSignedData().ContentInfo); Evidence evidence = new Evidence(new TimeStampTokenEvidence(timeStampAndCrl)); TimeStampedData timeStampedDatum = new TimeStampedData(derIA5String, null, berOctetStrings, evidence); return((new ContentInfo(CmsObjectIdentifiers.timestampedData, timeStampedDatum)).GetEncoded()); }
//-------------------------------------------------------------------------------------------------------------------------// // //-------------------------------------------------------------------------------------------------------------------------// /// <summary> /// RFC 3852의 EnvelopedData 구조체 중 EncryptedContentInfo 항목을 생성한다. /// </summary> /// <param name="encrypted_content">암호화된 데이터</param> /// <param name="init_vector">암호화에 사용된 IV 값</param> /// <returns></returns> private EncryptedContentInfo GetEncryptedContentInfo(byte[] encrypted_content, byte[] init_vector) { // EncryptedContentInfo 에 포함된 데이터의 타입을 가리키는 OID // 표준전자세금계산서 개발지침(v1.0) 56페이지 참조 DerObjectIdentifier _contentType = new DerObjectIdentifier("1.2.840.113549.1.7.1"); // 실제 암호화에 이용된 대칭키 알고리즘 정보 설정 // 암호화 알고리즘 : 3DES // 3DES의 OID : 1.2.840.113549.3.7 Asn1OctetString _paramIV = new BerOctetString(init_vector); // 암호화 알고리즘의 파라미터(= 암호화에 사용된 초기벡터 값) 설정 AlgorithmIdentifier _contentEncryptionAlgorithm = new AlgorithmIdentifier(new DerObjectIdentifier("1.2.840.113549.3.7"), _paramIV); // 전자세금계산서 패키징 데이터를 암호화한 데이터 포함 Asn1OctetString _encryptedContent = new BerOctetString(encrypted_content); // EncryptedContentInfo 구조체를 설정한다. return(new EncryptedContentInfo(_contentType, _contentEncryptionAlgorithm, _encryptedContent)); }
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)); }
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)); }
private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_009f: Expected O, but got Unknown 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 var _); IMac mac = MacUtilities.GetMac(macOid); mac.Init(keyParameter); MemoryStream val = new MemoryStream(); Stream val2 = (Stream)(object)new TeeOutputStream((Stream)(object)val, (Stream)(object)new MacOutputStream(mac)); content.Write(val2); Platform.Dispose(val2); content2 = new BerOctetString(val.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 val3) { IOException e3 = val3; 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(); } } 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)); }
/// <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 = null; 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)); }
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)); }
public CmsSignedData Generate(string signedContentType, CmsProcessable content, bool encapsulate) { Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]); Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[0]); this._digests.Clear(); foreach (SignerInformation signerInformation in this._signers) { asn1EncodableVector.Add(new Asn1Encodable[] { CmsSignedDataGenerator.Helper.FixAlgID(signerInformation.DigestAlgorithmID) }); asn1EncodableVector2.Add(new Asn1Encodable[] { signerInformation.ToSignerInfo() }); } DerObjectIdentifier contentType = (signedContentType == null) ? null : new DerObjectIdentifier(signedContentType); foreach (CmsSignedDataGenerator.SignerInf signerInf in this.signerInfs) { try { asn1EncodableVector.Add(new Asn1Encodable[] { signerInf.DigestAlgorithmID }); asn1EncodableVector2.Add(new Asn1Encodable[] { signerInf.ToSignerInfo(contentType, content, this.rand) }); } catch (IOException e) { throw new CmsException("encoding error.", 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); } } Asn1Set certificates = null; if (this._certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(this._certs); } Asn1Set crls = null; if (this._crls.Count != 0) { crls = CmsUtilities.CreateBerSetFromList(this._crls); } Asn1OctetString content2 = null; if (encapsulate) { MemoryStream memoryStream = new MemoryStream(); if (content != null) { try { content.Write(memoryStream); } catch (IOException e5) { throw new CmsException("encapsulation error.", e5); } } content2 = new BerOctetString(memoryStream.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)); }
/** * 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 void Save( Stream stream, char[] password, SecureRandom random) { if (stream == null) { throw new ArgumentNullException("stream"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } ContentInfo[] c = new ContentInfo[2]; // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); foreach (string name in keys.Keys) { byte[] kSalt = new byte[saltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name]; EncryptedPrivateKeyInfo kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( keyAlgorithm, password, kSalt, minIterations, privKey.Key); Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { kName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(privKey[oid]))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = GetCertificate(name); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( ct.Certificate.GetPublicKey()); kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(new SubjectKeyIdentifier(info)))); } // // make sure we are using the local alias on store // DerBmpString nm = (DerBmpString)privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName]; if (nm == null || !nm.GetString().Equals(name)) { kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); BerOctetString keyString = new BerOctetString(derEncodedBytes); // // certificate processing // byte[] cSalt = new byte[saltSize]; random.NextBytes(cSalt); Asn1EncodableVector certSeq = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, minIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object()); Hashtable doneCerts = new Hashtable(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509CertType, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(certEntry[oid]))); } // // make sure we are using the local alias on store // DerBmpString nm = (DerBmpString)certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName]; if (nm == null || !nm.GetString().Equals(name)) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( certEntry.Certificate.GetPublicKey()); fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(new SubjectKeyIdentifier(info)))); } SafeBag sBag = new SafeBag( PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate, certEntry.Certificate); } foreach (string certId in certs.Keys) { X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; if (keys[certId] != null) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509CertType, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } // // make sure we are using the local alias on store // DerBmpString nm = (DerBmpString)cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName]; if (nm == null || !nm.GetString().Equals(certId)) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert, cert); } foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts[cert] != null) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509CertType, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); byte[] certBytes = EncryptData(new AlgorithmIdentifier(certAlgorithm, cParams), derEncodedBytes, password); EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, keyString); c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()); AuthenticatedSafe auth = new AuthenticatedSafe(c); byte[] pkg = auth.GetEncoded(); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(pkg)); // // create the mac // byte[] mSalt = new byte[20]; int itCount = minIterations; random.NextBytes(mSalt); byte[] data = ((Asn1OctetString)mainInfo.Content).GetOctets(); MacData mData = null; Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters(OiwObjectIdentifiers.IdSha1, mSalt, itCount); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( OiwObjectIdentifiers.IdSha1, password, parameters); IMac mac = (IMac)PbeUtilities.CreateEngine(OiwObjectIdentifiers.IdSha1); mac.Init(keyParameters); mac.BlockUpdate(data, 0, data.Length); byte[] res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, res); mData = new MacData(dInfo, mSalt, itCount); // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); BerOutputStream berOut = new BerOutputStream(stream); berOut.WriteObject(pfx); }
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)); }
/// <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)); }
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)); }
/** * 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)); }
public void Save( Stream stream, char[] password, SecureRandom random) { if (stream == null) { throw new ArgumentNullException("stream"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); foreach (string name in keys.Keys) { byte[] kSalt = new byte[SaltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name]; EncryptedPrivateKeyInfo kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( keyAlgorithm, password, kSalt, MinIterations, privKey.Key); Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { Asn1Encodable entry = privKey[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } kName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = GetCertificate(name); IAsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); BerOctetString keyString = new BerOctetString(derEncodedBytes); // // certificate processing // byte[] cSalt = new byte[SaltSize]; random.NextBytes(cSalt); Asn1EncodableVector certSeq = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, MinIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object()); ISet doneCerts = new HashSet(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { Asn1Encodable entry = certEntry[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { IAsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag sBag = new SafeBag( PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate); } foreach (string certId in certs.Keys) { X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; if (keys[certId] != null) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } Asn1Encodable entry = cert[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'certId' //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert.Certificate); } foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts.Contains(cert.Certificate)) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); byte[] certBytes = CryptPbeData(true, cAlgId, password, false, derEncodedBytes); EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); ContentInfo[] info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()) }; byte[] data = new AuthenticatedSafe(info).GetEncoded( useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data)); // // create the mac // byte[] mSalt = new byte[20]; random.NextBytes(mSalt); byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, MinIterations, password, false, data); AlgorithmIdentifier algId = new AlgorithmIdentifier( OiwObjectIdentifiers.IdSha1, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, mac); MacData mData = new MacData(dInfo, mSalt, MinIterations); // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); DerOutputStream derOut; if (useDerEncoding) { derOut = new DerOutputStream(stream); } else { derOut = new BerOutputStream(stream); } derOut.WriteObject(pfx); }
public static void Save(this Pkcs12Store store, Stream stream, string encryptionPassword, string integrityPassword, SecureRandom random) { const int saltSize = 20; const int minIterations = 1024; if (stream == null) { throw new ArgumentNullException("stream"); } //if (null != encryptionPassword && encryptionPassword == integrityPassword) //{ // store.Save(stream, encryptionPassword.ToArray(), random); // return; //} if (random == null) { throw new ArgumentNullException("random"); } var T = store.GetType(); Func <AsymmetricKeyParameter, SubjectKeyIdentifier> CreateSubjectKeyID = (pubKey_) => { var method = T.GetMethod("CreateSubjectKeyID", BindingFlags.NonPublic | BindingFlags.Static); return((SubjectKeyIdentifier)method.Invoke(store, new object[] { pubKey_ })); }; Func <DerObjectIdentifier> keyAlgorithm = () => { var property = T.GetField("keyAlgorithm", BindingFlags.NonPublic | BindingFlags.Instance); return((DerObjectIdentifier)property.GetValue(store)); }; Func <DerObjectIdentifier> certAlgorithm = () => { var property = T.GetField("certAlgorithm", BindingFlags.NonPublic | BindingFlags.Instance); return((DerObjectIdentifier)property.GetValue(store)); }; // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); var keys = store.Aliases.OfType <string>().ToDictionary(alias => alias, store.GetKey); foreach (string name in store.Aliases.OfType <string>()) { byte[] kSalt = new byte[saltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = keys[name]; Asn1Encodable kInfo = null; if (!string.IsNullOrEmpty(encryptionPassword)) { kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(keyAlgorithm(), encryptionPassword.ToArray(), kSalt, minIterations, privKey.Key); } else { kInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key); } Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { Asn1Encodable entry = privKey[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } kName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { kName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = store.GetCertificate(name); AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); kName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag kBag = null; if (!string.IsNullOrEmpty(encryptionPassword)) { kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); } else { kBag = new SafeBag(PkcsObjectIdentifiers.KeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); } keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); BerOctetString keyString = new BerOctetString(derEncodedBytes); // // certificate processing // byte[] cSalt = new byte[saltSize]; random.NextBytes(cSalt); Asn1EncodableVector certSeq = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, minIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm(), cParams.ToAsn1Object()); ISet doneCerts = new HashSet(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = store.GetCertificate(name); CertBag cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { Asn1Encodable entry = certEntry[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate); } var certs = store.Aliases.OfType <string>().Select(store.GetCertificate); foreach (var cert in certs) { //X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; //if (keys[certId] != null) // continue; if (doneCerts.Contains(cert.Certificate)) { continue; } CertBag cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } Asn1Encodable entry = cert[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'certId' //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { //fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(CreateSubjectKeyID(cert.Certificate.GetPublicKey()).GetKeyIdentifier())))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert.Certificate); } var chainCerts = store.Aliases.OfType <string>().Select(store.GetCertificateChain).Aggregate <IEnumerable <X509CertificateEntry>, IEnumerable <X509CertificateEntry> >(new List <X509CertificateEntry>(), (list, entries) => list.Union(entries)); foreach (var cert in chainCerts) { //X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts.Contains(cert.Certificate)) { continue; } CertBag cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); Func <bool, AlgorithmIdentifier, char[], bool, byte[], byte[]> CryptPbeData = (forEncryption_, algId_, password_, wrongPkcs12Zero_, data_) => { var method = T.GetMethod("CryptPbeData", BindingFlags.NonPublic | BindingFlags.Static); return((byte[])method.Invoke(store, new object[] { forEncryption_, algId_, password_, wrongPkcs12Zero_, data_ })); }; ContentInfo[] info = null; if (null != encryptionPassword) { byte[] certBytes = CryptPbeData(true, cAlgId, encryptionPassword.ToArray(), false, derEncodedBytes); var cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()) }; } else { var cInfo = new BerOctetString(derEncodedBytes); info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.Data, cInfo.ToAsn1Object()) }; } byte[] data = new AuthenticatedSafe(info).GetEncoded(Asn1Encodable.Der); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data)); // // create the mac // byte[] mSalt = new byte[saltSize]; random.NextBytes(mSalt); Func <DerObjectIdentifier, byte[], int, char[], bool, byte[], byte[]> CalculatePbeMac = (oid_, salt_, itCount_, password_, wrongPkcs12Zero_, data_) => { var method = T.GetMethod("CalculatePbeMac", BindingFlags.NonPublic | BindingFlags.Static); return((byte[])method.Invoke(store, new object[] { oid_, salt_, itCount_, password_, wrongPkcs12Zero_, data_ })); }; MacData mData = null; if (null != integrityPassword) { //byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, minIterations, integrityPassword.ToArray(), false, data); byte[] mac = CalculatePbeMac(PbeUtilities.GetObjectIdentifier("PBEwithHmacSHA-256"), mSalt, minIterations, integrityPassword.ToArray(), false, data); //AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); AlgorithmIdentifier algId = new AlgorithmIdentifier(PbeUtilities.GetObjectIdentifier("PBEwithHmacSHA-256"), DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, mac); mData = new MacData(dInfo, mSalt, minIterations); } // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); DerOutputStream derOut = new DerOutputStream(stream); derOut.WriteObject(pfx); }
/** * 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)); }
/** * 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( // FIXME Avoid accessing more than once to support CmsProcessableInputStream ICmsTypedData content, bool encapsulate) { // TODO // if (signerInfs.isEmpty()) // { // /* RFC 3852 5.2 // * "In the degenerate case where there are no signers, the // * EncapsulatedContentInfo value being "signed" is irrelevant. In this // * case, the content type within the EncapsulatedContentInfo value being // * "signed" MUST be id-data (as defined in section 4), and the content // * field of the EncapsulatedContentInfo value MUST be omitted." // */ // if (encapsulate) // { // throw new IllegalArgumentException("no signers, encapsulate must be false"); // } // if (!DATA.equals(eContentType)) // { // throw new IllegalArgumentException("no signers, eContentType must be id-data"); // } // } // // if (!DATA.equals(eContentType)) // { // /* RFC 3852 5.3 // * [The 'signedAttrs']... // * field is optional, but it MUST be present if the content type of // * the EncapsulatedContentInfo value being signed is not id-data. // */ // // TODO signedAttrs must be present for all signers // } Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); _digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. // for (IEnumerator it = _signers.GetEnumerator(); it.MoveNext();) { SignerInformation signer = (SignerInformation)it.Current; digestAlgs.Add(CmsUtilities.fixAlgID(signer.DigestAlgorithmID)); // TODO Verify the content type and calculated digest match the precalculated SignerInfo signerInfos.Add(signer.ToAsn1Structure()); } // // add the SignerInfo objects // DerObjectIdentifier contentTypeOID = content.ContentType; Asn1OctetString octs = null; if (content.GetContent() != null) { MemoryOutputStream bOut = null; if (encapsulate) { bOut = new MemoryOutputStream(); } Stream cOut = CmsUtilities.attachSignersToOutputStream(_signerGens, bOut); // Just in case it's unencapsulated and there are no signers! cOut = CmsUtilities.getSafeOutputStream(cOut); try { content.Write(cOut); cOut.Close(); } catch (IOException e) { throw new CmsException("data processing exception: " + e.Message, e); } if (encapsulate) { octs = new BerOctetString(bOut.ToArray()); } } for (IEnumerator it = _signerGens.GetEnumerator(); it.MoveNext();) { SignerInfoGenerator sGen = (SignerInfoGenerator)it.Current; SignerInfo inf = sGen.Generate(contentTypeOID); digestAlgs.Add(inf.DigestAlgorithm); signerInfos.Add(inf); byte[] calcDigest = sGen.getCalculatedDigest(); if (calcDigest != null) { _digests.Add(inf.DigestAlgorithm.Algorithm.Id, calcDigest); } } Asn1Set certificates = null; if (_certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set certrevlist = null; if (_crls.Count != 0) { certrevlist = CmsUtilities.CreateBerSetFromList(_crls); } 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)); }