Inheritance: Org.BouncyCastle.Asn1.Asn1Encodable
		public TimeStampResp(
			PkiStatusInfo	pkiStatusInfo,
			ContentInfo		timeStampToken)
		{
			this.pkiStatusInfo = pkiStatusInfo;
			this.timeStampToken = timeStampToken;
		}
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="x509_certificate2"></param>
        /// <param name="encrypted_data"></param>
        /// <returns></returns>
        public byte[] GetDecryptedContent(X509Certificate2 x509_certificate2, byte[] encrypted_data)
        {
            Org.BouncyCastle.Asn1.Cms.ContentInfo _content = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(Asn1Sequence.FromByteArray(encrypted_data));

            EnvelopedData _envelopedData = EnvelopedData.GetInstance(_content.Content);

            EncryptedContentInfo _encryptedContentInfo = _envelopedData.EncryptedContentInfo;

            byte[] _encrypt = _encryptedContentInfo.EncryptedContent.GetOctets();

            RecipientInfo         _recipientInfo         = RecipientInfo.GetInstance(_envelopedData.RecipientInfos[0]);
            KeyTransRecipientInfo _keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(_recipientInfo.Info);

            byte[] _byteEncryptedKey = _keyTransRecipientInfo.EncryptedKey.GetOctets();

            RSACryptoServiceProvider _rsaCrypto = (RSACryptoServiceProvider)x509_certificate2.PrivateKey;

            byte[] _randomKey = _rsaCrypto.Decrypt(_byteEncryptedKey, false);

            AlgorithmIdentifier _contentEncryptionAlgorithm = _encryptedContentInfo.ContentEncryptionAlgorithm;
            Asn1OctetString     _paramIV = Asn1OctetString.GetInstance(_contentEncryptionAlgorithm.Parameters);

            byte[] _initVector = _paramIV.GetOctets();

            tDESCrypto _cryptoService = new tDESCrypto(_randomKey, _initVector);

            return(_cryptoService.Decrypt(_encrypt));
        }
示例#3
0
		public CmsAuthenticatedData(
			ContentInfo contentInfo)
		{
			this.contentInfo = contentInfo;

			AuthenticatedData authData = AuthenticatedData.GetInstance(contentInfo.Content);

			//
			// read the recipients
			//
			Asn1Set recipientInfos = authData.RecipientInfos;

			this.macAlg = authData.MacAlgorithm;

			//
			// read the authenticated content info
			//
			ContentInfo encInfo = authData.EncapsulatedContentInfo;
			CmsReadable readable = new CmsProcessableByteArray(
				Asn1OctetString.GetInstance(encInfo.Content).GetOctets());
			CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsAuthenticatedSecureReadable(
				this.macAlg, readable);

			//
			// build the RecipientInformationStore
			//
			this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
				recipientInfos, secureReadable);

			this.authAttrs = authData.AuthAttrs;
			this.mac = authData.Mac.GetOctets();
			this.unauthAttrs = authData.UnauthAttrs;
		}
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

			EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

			//
			// read the recipients
			//
			Asn1Set recipientInfos = envData.RecipientInfos;

			//
			// read the encrypted content info
			//
			EncryptedContentInfo encInfo = envData.EncryptedContentInfo;
			this.encAlg = encInfo.ContentEncryptionAlgorithm;
			CmsReadable readable = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
			CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(
				this.encAlg, readable);

			//
			// build the RecipientInformationStore
			//
			this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
				recipientInfos, secureReadable);

			this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
		public CompressedData(
            Asn1Sequence seq)
        {
            this.version = (DerInteger) seq[0];
            this.compressionAlgorithm = AlgorithmIdentifier.GetInstance(seq[1]);
            this.encapContentInfo = ContentInfo.GetInstance(seq[2]);
        }
示例#6
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual byte[] GetArchiveTimestampData(int index, Document originalDocument
                                                      )
        {
            ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

            BcCms.ContentInfo contentInfo = cmsSignedData.ContentInfo;
            BcCms.SignedData  signedData  = BcCms.SignedData.GetInstance(contentInfo.Content);
            // 5.4.1
            if (signedData.EncapContentInfo == null || signedData.EncapContentInfo.
                Content == null)
            {
                if (originalDocument != null)
                {
                    //jbonilla Hack para leer un InputStream en su totalidad.
                    toTimestamp.Write(Streams.ReadAll(
                                          originalDocument.OpenStream()));
                }
                else
                {
                    throw new RuntimeException("Signature is detached and no original data provided."
                                               );
                }
            }
            else
            {
                BcCms.ContentInfo content = signedData.EncapContentInfo;
                DerOctetString    octet   = (DerOctetString)content.Content;
                BcCms.ContentInfo info2   = new BcCms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1"
                                                                                          ), new BerOctetString(octet.GetOctets()));
                toTimestamp.Write(info2.GetEncoded());
            }
            if (signedData.Certificates != null)
            {
                DerOutputStream output = new DerOutputStream(toTimestamp);
                output.WriteObject(signedData.Certificates);
                output.Close();
            }
            if (signedData.CRLs != null)
            {
                toTimestamp.Write(signedData.CRLs.GetEncoded());
            }
            if (signerInformation.UnsignedAttributes != null)
            {
                Asn1EncodableVector     original          = signerInformation.UnsignedAttributes.ToAsn1EncodableVector();
                IList <BcCms.Attribute> timeStampToRemove = GetTimeStampToRemove(index);
                Asn1EncodableVector     filtered          = new Asn1EncodableVector();
                for (int i = 0; i < original.Count; i++)
                {
                    Asn1Encodable enc = original[i];
                    if (!timeStampToRemove.Contains(enc))
                    {
                        filtered.Add(original[i]);
                    }
                }
                SignerInformation filteredInfo = SignerInformation.ReplaceUnsignedAttributes(signerInformation
                                                                                             , new BcCms.AttributeTable(filtered));
                toTimestamp.Write(filteredInfo.ToSignerInfo().GetEncoded());
            }
            return(toTimestamp.ToByteArray());
        }
        /**
        * 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);
        }
示例#8
0
		public CmsAuthEnvelopedData(
			ContentInfo contentInfo)
		{
			this.contentInfo = contentInfo;

			AuthEnvelopedData authEnvData = AuthEnvelopedData.GetInstance(contentInfo.Content);

			this.originator = authEnvData.OriginatorInfo;

			//
	        // read the recipients
	        //
	        Asn1Set recipientInfos = authEnvData.RecipientInfos;

			//
			// read the auth-encrypted content info
			//
			EncryptedContentInfo authEncInfo = authEnvData.AuthEncryptedContentInfo;
			this.authEncAlg = authEncInfo.ContentEncryptionAlgorithm;
			CmsSecureReadable secureReadable = new AuthEnvelopedSecureReadable(this);

			//
			// build the RecipientInformationStore
			//
			this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
				recipientInfos, secureReadable);

			// FIXME These need to be passed to the AEAD cipher as AAD (Additional Authenticated Data)
			this.authAttrs = authEnvData.AuthAttrs;
			this.mac = authEnvData.Mac.GetOctets();
			this.unauthAttrs = authEnvData.UnauthAttrs;
		}
		public AuthenticatedData(
			OriginatorInfo		originatorInfo,
			Asn1Set				recipientInfos,
			AlgorithmIdentifier	macAlgorithm,
			AlgorithmIdentifier	digestAlgorithm,
			ContentInfo			encapsulatedContent,
			Asn1Set				authAttrs,
			Asn1OctetString		mac,
			Asn1Set				unauthAttrs)
		{
			if (digestAlgorithm != null || authAttrs != null)
			{
				if (digestAlgorithm == null || authAttrs == null)
				{
					throw new ArgumentException("digestAlgorithm and authAttrs must be set together");
				}
			}

			version = new DerInteger(CalculateVersion(originatorInfo));

			this.originatorInfo = originatorInfo;
			this.macAlgorithm = macAlgorithm;
			this.digestAlgorithm = digestAlgorithm;
			this.recipientInfos = recipientInfos;
			this.encapsulatedContentInfo = encapsulatedContent;
			this.authAttrs = authAttrs;
			this.mac = mac;
			this.unauthAttrs = unauthAttrs;
		}
示例#10
0
		private CmsSignedData(
			CmsSignedData c)
		{
			this.signedData = c.signedData;
			this.contentInfo = c.contentInfo;
			this.signedContent = c.signedContent;
			this.signerInfoStore = c.signerInfoStore;
		}
示例#11
0
		private TimeStampAndCrl(Asn1Sequence seq)
		{
			this.timeStamp = ContentInfo.GetInstance(seq[0]);
			if (seq.Count == 2)
			{
				this.crl = X509.CertificateList.GetInstance(seq[1]);
			}
		}
示例#12
0
		public CompressedData(
            AlgorithmIdentifier	compressionAlgorithm,
            ContentInfo			encapContentInfo)
        {
            this.version = new DerInteger(0);
            this.compressionAlgorithm = compressionAlgorithm;
            this.encapContentInfo = encapContentInfo;
        }
示例#13
0
		private TimeStampResp(
			Asn1Sequence seq)
		{
			this.pkiStatusInfo = PkiStatusInfo.GetInstance(seq[0]);

			if (seq.Count > 1)
			{
				this.timeStampToken = ContentInfo.GetInstance(seq[1]);
			}
		}
示例#14
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

            //
            // read the encrypted content info
            //
            EncryptedContentInfo encInfo = envData.EncryptedContentInfo;

            this.encAlg = encInfo.ContentEncryptionAlgorithm;

            //
            // load the RecipientInfoStore
            //
            Asn1Set	s = envData.RecipientInfos;
            IList infos = new ArrayList();
            byte[] contentOctets = encInfo.EncryptedContent.GetOctets();

            foreach (Asn1Encodable ae in s)
            {
                RecipientInfo info = RecipientInfo.GetInstance(ae);
                MemoryStream contentStream = new MemoryStream(contentOctets, false);

                object type = info.Info;

                if (type is KeyTransRecipientInfo)
                {
                    infos.Add(new KeyTransRecipientInformation(
                        (KeyTransRecipientInfo) type, encAlg, contentStream));
                }
                else if (type is KekRecipientInfo)
                {
                    infos.Add(new KekRecipientInformation(
                        (KekRecipientInfo) type, encAlg, contentStream));
                }
                else if (type is KeyAgreeRecipientInfo)
                {
                    infos.Add(new KeyAgreeRecipientInformation(
                        (KeyAgreeRecipientInfo) type, encAlg, contentStream));
                }
                else if (type is PasswordRecipientInfo)
                {
                    infos.Add(new PasswordRecipientInformation(
                        (PasswordRecipientInfo) type, encAlg, contentStream));
                }
            }

            this.recipientInfoStore = new RecipientInformationStore(infos);
            this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
示例#15
0
 private ScvpReqRes(Asn1Sequence seq)
 {
     if (seq[0] is Asn1TaggedObject)
     {
         this.request = ContentInfo.GetInstance(Asn1TaggedObject.GetInstance(seq[0]), true);
         this.response = ContentInfo.GetInstance(seq[1]);
     }
     else
     {
         this.request = null;
         this.response = ContentInfo.GetInstance(seq[0]);
     }
 }
示例#16
0
        public SignedData(
			Asn1Set     digestAlgorithms,
			ContentInfo contentInfo,
			Asn1Set     certificates,
			Asn1Set     crls,
			Asn1Set     signerInfos)
        {
            this.version = CalculateVersion(contentInfo.ContentType, certificates, crls, signerInfos);
            this.digestAlgorithms = digestAlgorithms;
            this.contentInfo = contentInfo;
            this.certificates = certificates;
            this.crls = crls;
            this.signerInfos = signerInfos;
        }
        private Asn1Encodable CreateDERForRecipient(byte[] inp, X509Certificate cert)
        {
            string algorithm = PkcsObjectIdentifiers.RC2Cbc.Id;
            Pkcs12ParametersGenerator apg;
            CipherKeyGenerator        keygen;
            IBufferedCipher           cipher;

            try
            {
                apg    = new Pkcs12ParametersGenerator(new Sha1Digest());//TODO Check
                keygen = GeneratorUtilities.GetKeyGenerator(algorithm);
                cipher = CipherUtilities.GetCipher(algorithm);
            }
            catch (Exception e)
            {
                // happens when using the command line app .jar file
                throw new IOException("Could not find a suitable javax.crypto provider for algorithm " +
                                      algorithm + "; possible reason: using an unsigned .jar file", e);
            }

            //TODO apg.Init(PbeParametersGenerator.Pkcs12PasswordToBytes(password), salt, iCount);

            var parameters = apg.GenerateDerivedParameters(algorithm, inp.Length * 8);

            Asn1Encodable obj = null;

            //TODO
            //using (Asn1InputStream input = new Asn1InputStream(parameters.getEncoded("ASN.1")))
            //{
            //    obj = input.ReadObject();
            //}

            keygen.Init(new KeyGenerationParameters(new SecureRandom(), 128));
            var secretkey = keygen.GenerateKey();

            //TODO cipher.Init(true, secretkey, parameters);
            byte[] bytes = cipher.DoFinal(inp);

            var recipientInfo = ComputeRecipientInfo(cert, secretkey);
            var set           = new DerSet(new RecipientInfo(recipientInfo));

            var algorithmId   = new AlgorithmIdentifier(new DerObjectIdentifier(algorithm), obj);
            var encryptedInfo = new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmId, new DerOctetString(bytes));
            var enveloped     = new EnvelopedData(null, set, encryptedInfo, (Asn1Set)null);

            var contentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, enveloped);

            return(contentInfo.Content);
        }
示例#18
0
        private SignedData(
            Asn1Sequence seq)
        {
            IEnumerator e = seq.GetEnumerator();

            e.MoveNext();
            version = (DerInteger)e.Current;

            e.MoveNext();
            digestAlgorithms = ((Asn1Set)e.Current);

            e.MoveNext();
            contentInfo = ContentInfo.GetInstance(e.Current);

            while (e.MoveNext())
            {
                Asn1Object o = (Asn1Object)e.Current;

                //
                // an interesting feature of SignedData is that there appear
                // to be varying implementations...
                // for the moment we ignore anything which doesn't fit.
                //
                if (o is Asn1TaggedObject)
                {
                    Asn1TaggedObject tagged = (Asn1TaggedObject)o;

                    switch (tagged.TagNo)
                    {
                        case 0:
                            certBer = tagged is BerTaggedObject;
                            certificates = Asn1Set.GetInstance(tagged, false);
                            break;
                        case 1:
                            crlsBer = tagged is BerTaggedObject;
                            crls = Asn1Set.GetInstance(tagged, false);
                            break;
                        default:
                            throw new ArgumentException("unknown tag value " + tagged.TagNo);
                    }
                }
                else
                {
                    signerInfos = (Asn1Set) o;
                }
            }
        }
	    private AuthenticatedData(
	        Asn1Sequence seq)
	    {
	        int index = 0;

	        version = (DerInteger)seq[index++];

	        Asn1Encodable tmp = seq[index++];

	        if (tmp is Asn1TaggedObject)
	        {
	            originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false);
	            tmp = seq[index++];
	        }

	        recipientInfos = Asn1Set.GetInstance(tmp);
	        macAlgorithm = AlgorithmIdentifier.GetInstance(seq[index++]);

	        tmp = seq[index++];

	        if (tmp is Asn1TaggedObject)
	        {
	            digestAlgorithm = AlgorithmIdentifier.GetInstance((Asn1TaggedObject)tmp, false);
	            tmp = seq[index++];
	        }

	        encapsulatedContentInfo = ContentInfo.GetInstance(tmp);

	        tmp = seq[index++];

	        if (tmp is Asn1TaggedObject)
	        {
	            authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false);
	            tmp = seq[index++];
	        }

	        mac = Asn1OctetString.GetInstance(tmp);
	        
	        if (seq.Count > index)
	        {
	            unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)seq[index], false);
	        }
	    }
示例#20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="x509_certificate2"></param>
        /// <param name="plain_data"></param>
        /// <returns></returns>
        public byte[] GetEncryptedContent(X509Certificate2 x509_certificate2, byte[] plain_data)
        {
            tDESCrypto _cryptoService = new tDESCrypto();

            // RecipientInfo 구조체 생성 및 설정
            RecipientInfo _recipientInfo = this.GetKeyTransRecipientInfo(x509_certificate2, _cryptoService.Key);

            // EncryptedContentInfo 구조체 생성 및 설정
            DerOctetString _taxInvoce = new DerOctetString(plain_data);

            byte[] _package = _taxInvoce.GetOctets();
            byte[] _encrypt = _cryptoService.Encrypt(_package);                       // 대칭키로 암호화
            EncryptedContentInfo _encryptedContentInfo = this.GetEncryptedContentInfo(_encrypt, _cryptoService.IV);

            // EnvelopedData 구조체 생성 및 설정
            Asn1Set       _receipientInfos = new DerSet(_recipientInfo);
            EnvelopedData _envelopedData   = new EnvelopedData((OriginatorInfo)null, _receipientInfos, _encryptedContentInfo, (Asn1Set)null);

            Org.BouncyCastle.Asn1.Cms.ContentInfo _content = new Org.BouncyCastle.Asn1.Cms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.3"), _envelopedData);
            return(_content.GetEncoded());
        }
示例#21
0
        //-------------------------------------------------------------------------------------------------------------------------//
        //
        //-------------------------------------------------------------------------------------------------------------------------//

        /// <summary>
        /// RFC 3852 CMS 에 정의된 ContentInfo 구조체를 생성한다.
        /// </summary>
        /// <param name="x509_certificate2">랜덤키를 암호화하기 위한 공인인증서(국세청 공인인증서)</param>
        /// <param name="plain_data">데이터</param>
        /// <returns></returns>
        public byte[] GetContentInfo(X509Certificate2 x509_certificate2, ArrayList plain_data)
        {
            tDESCrypto _cryptoService = new tDESCrypto();

            // RecipientInfo 구조체 생성 및 설정
            RecipientInfo _recipientInfo = this.GetKeyTransRecipientInfo(x509_certificate2, _cryptoService.Key);

            // EncryptedContentInfo 구조체 생성 및 설정
            byte[] _package = this.GetTaxInvoicePackage(plain_data);
            byte[] _encrypt = _cryptoService.Encrypt(_package);                       // 대칭키로 암호화
            EncryptedContentInfo _encryptedContentInfo = this.GetEncryptedContentInfo(_encrypt, _cryptoService.IV);

            // EnvelopedData 구조체 생성 및 설정
            Asn1Set       _asn1Set  = new DerSet(_recipientInfo);
            EnvelopedData _envelope = new EnvelopedData((OriginatorInfo)null, _asn1Set, _encryptedContentInfo, (Asn1Set)null);

            // RFC 3852의 구성 데이터인 SignedData, EnvelopedData, EncryptedData 등을 넣어주는 컨테이너인 ContentInfo 구조체를 생성 및 설정한다.
            // ContentInfo 구조체는 표준전자세금계산서 개발지침(v1.0)의 58페이지 참조
            Org.BouncyCastle.Asn1.Cms.ContentInfo _content = new Org.BouncyCastle.Asn1.Cms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.3"), _envelope);
            return(_content.GetEncoded());
        }
示例#22
0
        private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert)
        {
            String s = "1.2.840.113549.3.2";

            byte[] outp = new byte[100];
            DerObjectIdentifier derob = new DerObjectIdentifier(s);

            byte[]          keyp = IVGenerator.GetIV(16);
            IBufferedCipher cf   = CipherUtilities.GetCipher(derob);
            KeyParameter    kp   = new KeyParameter(keyp);

            byte[]           iv  = IVGenerator.GetIV(cf.GetBlockSize());
            ParametersWithIV piv = new ParametersWithIV(kp, iv);

            cf.Init(true, piv);
            int len = cf.DoFinal(inp, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString        deroctetstring        = new DerOctetString(abyte1);
            KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp);
            DerSet derset          = new DerSet(new RecipientInfo(keytransrecipientinfo));
            Asn1EncodableVector ev = new Asn1EncodableVector();

            ev.Add(new DerInteger(58));
            ev.Add(new DerOctetString(iv));
            DerSequence          seq = new DerSequence(ev);
            AlgorithmIdentifier  algorithmidentifier  = new AlgorithmIdentifier(derob, seq);
            EncryptedContentInfo encryptedcontentinfo =
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);
            Asn1Set       set = null;
            EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);

            Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo =
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);
            return(contentinfo.ToAsn1Object());
        }
示例#23
0
        private Asn1Object createDerForRecipient(byte[] inp, X509Certificate cert)
        {
            var s = "1.2.840.113549.3.2";

            var outp  = new byte[100];
            var derob = new DerObjectIdentifier(s);
            var keyp  = IvGenerator.GetIv(16);
            var cf    = CipherUtilities.GetCipher(derob);
            var kp    = new KeyParameter(keyp);
            var iv    = IvGenerator.GetIv(cf.GetBlockSize());
            var piv   = new ParametersWithIV(kp, iv);

            cf.Init(true, piv);
            var len = cf.DoFinal(inp, outp, 0);

            var abyte1 = new byte[len];

            System.Array.Copy(outp, 0, abyte1, 0, len);
            var deroctetstring        = new DerOctetString(abyte1);
            var keytransrecipientinfo = computeRecipientInfo(cert, keyp);
            var derset = new DerSet(new RecipientInfo(keytransrecipientinfo));
            var ev     = new Asn1EncodableVector
            {
                new DerInteger(58),
                new DerOctetString(iv)
            };
            var seq = new DerSequence(ev);
            var algorithmidentifier  = new AlgorithmIdentifier(derob, seq);
            var encryptedcontentinfo =
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);

            var env         = new EnvelopedData(null, derset, encryptedcontentinfo, (Asn1Set)null);
            var contentinfo =
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);

            return(contentinfo.ToAsn1Object());
        }
示例#24
0
    public static ICollection GetSignatureTimestamps(SignerInformation signerInfo)
    {
        IList list = Platform.CreateArrayList();

        Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes;
        if (unsignedAttributes != null)
        {
            foreach (Org.BouncyCastle.Asn1.Cms.Attribute item in unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken))
            {
                foreach (Asn1Encodable attrValue in item.AttrValues)
                {
                    try
                    {
                        Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(attrValue.ToAsn1Object());
                        TimeStampToken     timeStampToken = new TimeStampToken(instance);
                        TimeStampTokenInfo timeStampInfo  = timeStampToken.TimeStampInfo;
                        byte[]             a = DigestUtilities.CalculateDigest(GetDigestAlgName(timeStampInfo.MessageImprintAlgOid), signerInfo.GetSignature());
                        if (!Arrays.ConstantTimeAreEqual(a, timeStampInfo.GetMessageImprintDigest()))
                        {
                            throw new TspValidationException("Incorrect digest in message imprint");
                        }
                        list.Add(timeStampToken);
                    }
                    catch (SecurityUtilityException)
                    {
                        throw new TspValidationException("Unknown hash algorithm specified in timestamp");
                    }
                    catch (Exception)
                    {
                        throw new TspValidationException("Timestamp could not be parsed");
                    }
                }
            }
            return(list);
        }
        return(list);
    }
示例#25
0
 public ScvpReqRes(ContentInfo request, ContentInfo response)
 {
     this.request  = request;
     this.response = response;
 }
        public static byte[] PostSign(String digestAlgorithmName,
            byte[] content,
            X509Certificate2[] signerCertificateChain,
            byte[] signature,
            byte[] signedAttributes)
        {
            if (signerCertificateChain == null || signerCertificateChain.Length == 0)
            {
                throw new ArgumentException("La cadena de certificados debe contener al menos una entrada");
            }

            TbsCertificateStructure tbsCertificateStructure;

            //TODO Revisar esta parte del código
            /**
             *
             *  Revisar esta parte del código
             *
             */
            tbsCertificateStructure = TbsCertificateStructure.GetInstance(
                Asn1Object.FromByteArray(
                new Org.BouncyCastle.X509.X509Certificate(
                    X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(signerCertificateChain[0].GetRawCertData()))).GetTbsCertificate()
                    )
                    );

            SignerIdentifier signerIdentifier = new SignerIdentifier(
              new IssuerAndSerialNumber(X509Name.GetInstance(tbsCertificateStructure.Issuer), tbsCertificateStructure.SerialNumber)
               );

            // Algoritmo de huella digital
            AlgorithmIdentifier digestAlgorithmOID;
            digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName));

            // EncryptionAlgorithm
            AlgorithmIdentifier keyAlgorithmIdentifier;
            keyAlgorithmIdentifier = SigUtils.MakeAlgId(AOAlgorithmID.GetOID("RSA"));

            // Firma PKCS#1 codificada
            Asn1OctetString encodedPKCS1Signature = new DerOctetString(signature);

            // Atributos firmados
            Asn1Set asn1SignedAttributes;
            asn1SignedAttributes = (Asn1Set) Asn1Object.FromByteArray(signedAttributes);

            // SignerInfo
            Asn1EncodableVector signerInfo = new Asn1EncodableVector();
            signerInfo.Add(new SignerInfo(signerIdentifier, digestAlgorithmOID, asn1SignedAttributes, keyAlgorithmIdentifier, encodedPKCS1Signature, null));

            // ContentInfo
            ContentInfo contentInfo;
            if (content != null)
            {
                MemoryStream baos = new MemoryStream();
                CmsProcessable msg = new CmsProcessableByteArray(content);
                msg.Write(baos);

                contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), new BerOctetString(baos.ToArray()));
            }
            else
            {
                contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), null);
            }

            // Certificados
            List<Asn1Encodable> ce = new List<Asn1Encodable>();
            foreach (X509Certificate2 cert in signerCertificateChain)
            {
                /**
                 *
                 *  Revisar el uso que hacemos de X509CertificateStructure
                 *  ya que puede ser un posible punto de errores
                 *
                 */
                ce.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetRawCertData())));

            }
            Asn1Set certificates = SigUtils.CreateBerSetFromList(ce);

            // Algoritmos de huella digital
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();
            digestAlgorithms.Add(digestAlgorithmOID);

            return new ContentInfo(
               Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.SignedData,
               new SignedData(
                  new DerSet(digestAlgorithms),
                  contentInfo,
                  certificates,
                  null,
                  new DerSet(signerInfo)
               )
            ).GetEncoded("DER");
        }
示例#27
0
 public CompressedData(AlgorithmIdentifier compressionAlgorithm, ContentInfo encapContentInfo)
 {
     this.version = new DerInteger(0);
     this.compressionAlgorithm = compressionAlgorithm;
     this.encapContentInfo     = encapContentInfo;
 }
示例#28
0
 public CompressedData(Asn1Sequence seq)
 {
     this.version = (DerInteger)seq[0];
     this.compressionAlgorithm = AlgorithmIdentifier.GetInstance(seq[1]);
     this.encapContentInfo     = ContentInfo.GetInstance(seq[2]);
 }
 public TimeStampToken(Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo)
     : this(new CmsSignedData(contentInfo))
 {
 }
示例#30
0
        private void pkcs7Test()
        {
            Asn1Encodable rootCert = Asn1Object.FromByteArray(CertPathTest.rootCertBin);
            Asn1Encodable rootCrl = Asn1Object.FromByteArray(CertPathTest.rootCrlBin);

            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser crlParser = new X509CrlParser();

            SignedData sigData = new SignedData(
                DerSet.Empty,
                new ContentInfo(CmsObjectIdentifiers.Data, null),
                new DerSet(
                    rootCert,
                    new DerTaggedObject(false, 2, Asn1Object.FromByteArray(AttrCertTest.attrCert))),
                new DerSet(rootCrl),
                DerSet.Empty);

            ContentInfo info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            X509Certificate cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert == null || !AreEqual(cert.GetEncoded(), rootCert.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 cert not read");
            }
            X509Crl crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl == null || !AreEqual(crl.GetEncoded(), rootCrl.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 crl not read");
            }
            ArrayList col = new ArrayList(certParser.ReadCertificates(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(cert))
            {
                Fail("PKCS7 cert collection not right");
            }
            col = new ArrayList(crlParser.ReadCrls(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(crl))
            {
                Fail("PKCS7 crl collection not right");
            }

            // data with no certificates or CRLs

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), DerSet.Empty, DerSet.Empty, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            // data with absent certificates and CRLS

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), null, null, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            //
            // sample message
            //
            ICollection certCol = certParser.ReadCertificates(pkcs7CrlProblem);
            ICollection crlCol = crlParser.ReadCrls(pkcs7CrlProblem);

            if (crlCol.Count != 0)
            {
                Fail("wrong number of CRLs: " + crlCol.Count);
            }

            if (certCol.Count != 4)
            {
                Fail("wrong number of Certs: " + certCol.Count);
            }
        }
        private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert) {
            
            String s = "1.2.840.113549.3.2";
            
            byte[] outp = new byte[100];
            DerObjectIdentifier derob = new DerObjectIdentifier(s);
            byte[] keyp = IVGenerator.GetIV(16);
            IBufferedCipher cf = CipherUtilities.GetCipher(derob);
            KeyParameter kp = new KeyParameter(keyp);
            byte[] iv = IVGenerator.GetIV(cf.GetBlockSize());
            ParametersWithIV piv = new ParametersWithIV(kp, iv);
            cf.Init(true, piv);
            int len = cf.DoFinal(inp, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString deroctetstring = new DerOctetString(abyte1);
            KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp);
            DerSet derset = new DerSet(new RecipientInfo(keytransrecipientinfo));
            Asn1EncodableVector ev = new Asn1EncodableVector();
            ev.Add(new DerInteger(58));
            ev.Add(new DerOctetString(iv));
            DerSequence seq = new DerSequence(ev);
            AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(derob, seq);
            EncryptedContentInfo encryptedcontentinfo = 
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);
            Asn1Set set = null;
            EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
            Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo = 
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);
            return contentinfo.ToAsn1Object();        
        }
示例#32
0
		public TimeStampAndCrl(ContentInfo timeStamp)
		{
			this.timeStamp = timeStamp;
		}
示例#33
0
 public ScvpReqRes(ContentInfo response)
     : this(null, response)
 {
 }
示例#34
0
		private ITestResult SignedTest()
		{
			try
			{
				ContentInfo info = ContentInfo.GetInstance(
					Asn1Object.FromByteArray(signedData));
				SignedData sData = SignedData.GetInstance(info.Content);

				sData = new SignedData(sData.DigestAlgorithms, sData.EncapContentInfo, sData.Certificates, sData.CRLs, sData.SignerInfos);
				info = new ContentInfo(CmsObjectIdentifiers.SignedData, sData);

				if (!Arrays.AreEqual(info.GetEncoded(), signedData))
				{
					return new SimpleTestResult(false, Name + ": CMS signed failed to re-encode");
				}

				return new SimpleTestResult(true, Name + ": Okay");
			}
			catch (Exception e)
			{
				return new SimpleTestResult(false, Name + ": CMS signed failed - " + e.ToString(), e);
			}
		}
示例#35
0
		public CmsSignedData(
			ContentInfo sigData)
		{
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);

			//
			// this can happen if the signed message is sent simply to send a
			// certificate chain.
			//
			if (signedData.EncapContentInfo.Content != null)
			{
				this.signedContent = new CmsProcessableByteArray(
					((Asn1OctetString)(signedData.EncapContentInfo.Content)).GetOctets());
			}
//			else
//			{
//				this.signedContent = null;
//			}
		}
示例#36
0
		public CmsSignedData(
			IDictionary	hashes,
			ContentInfo	sigData)
		{
			this.hashes = hashes;
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);
		}
示例#37
0
        //var bcCert = CertificateUtilities.BuildBouncyCastleCollection(signingCertificates);
        //ICollection<Org.BouncyCastle.X509.X509Certificate>

        private SignedData CreateSignature(
            Session session,
            byte[] content,
            X509Certificate2Collection signingCertificates)
        {
            var digestOid     = ToDigestAlgorithmOid(DigestAlgorithm).Value;
            var hashGenerator = GetHashGenerator(DigestAlgorithm);
            var dataHash      = ComputeDigest(hashGenerator, content);

            // Construct SignerInfo.signedAttrs
            var signedAttributesVector = new Asn1EncodableVector();

            // Add PKCS#9 contentType signed attribute as Data
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtContentType.Id),
                    new DerSet(new DerObjectIdentifier(PkcsObjectIdentifiers.Data.Id))));

            // Add PKCS#9 messageDigest signed attribute with hash der string encoded
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtMessageDigest.Id),
                    new DerSet(new DerOctetString(dataHash))));

            // Add PKCS#9 signingTime signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtSigningTime.Id),
                    new DerSet(new Time(new DerUtcTime(DateTime.UtcNow)))));

            var signedAttributes = new DerSet(signedAttributesVector);



            // Sign SignerInfo.signedAttrs with PKCS#1 v1.5 RSA signature using private key stored on PKCS#11 compatible device
            byte[] pkcs1Digest     = ComputeDigest(hashGenerator, signedAttributes.GetDerEncoded());
            byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, digestOid);

            // Construct SignedData.digestAlgorithms
            var digestAlgorithmsVector = new Asn1EncodableVector();
            // Construct SignedData.certificates
            var certificatesVector = new Asn1EncodableVector();
            // Construct SignedData.signerInfos
            var signerInfosVector = new Asn1EncodableVector();

            // Construct SignedData.encapContentInfo
            var encapContentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(
                new DerObjectIdentifier(PkcsObjectIdentifiers.Data.Id),
                null); //Always a detached signature.


            foreach (var signingCertificate in signingCertificates)
            {
                var bcSigningCertificate = CertificateUtilities.ToBouncyCastleObject(signingCertificate.RawData);
                // Get public key from certificate
                var pubKeyParams = bcSigningCertificate.GetPublicKey(); //AsymmetricKeyParameter
                if (!(pubKeyParams is RsaKeyParameters))
                {
                    throw new NotSupportedException("Unsupported keys.  Currently supporting RSA keys only.");
                }

                var rsaPubKeyParams = (RsaKeyParameters)pubKeyParams;

                byte[] pkcs1Signature;

                if (signingCertificate.HasPrivateKey)
                {
                    pkcs1Signature = GeneratePkcs1Signature(signingCertificate, pkcs1DigestInfo);
                }
                else
                {
                    pkcs1Signature = GeneratePkcs1Signature(session, rsaPubKeyParams, bcSigningCertificate, pkcs1DigestInfo);
                }

                // Construct SignerInfo
                var signerInfo = new Org.BouncyCastle.Asn1.Cms.SignerInfo(
                    new SignerIdentifier(new IssuerAndSerialNumber(bcSigningCertificate.IssuerDN, bcSigningCertificate.SerialNumber)),
                    new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(digestOid), null),
                    signedAttributes,
                    new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(PkcsObjectIdentifiers.RsaEncryption.Id), null),
                    new DerOctetString(pkcs1Signature),
                    null);

                digestAlgorithmsVector.Add(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(digestOid), null));
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(bcSigningCertificate.GetEncoded())));
                signerInfosVector.Add(signerInfo.ToAsn1Object());
            }

            // Construct SignedData
            var signedData = new SignedData(
                new DerSet(digestAlgorithmsVector),
                encapContentInfo,
                new BerSet(certificatesVector),
                null,
                new DerSet(signerInfosVector));

            return(signedData);
        }
示例#38
0
 public ScvpReqRes(ContentInfo response) : this(null, response)
 {
 }
	    /**
	     * 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 CmsCompressedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;
        }
示例#41
0
 public static global::System.Collections.ICollection GetSignatureTimestamps(SignerInformation signerInfo)
 {
     global::System.Collections.IList         list = Platform.CreateArrayList();
     Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes;
     if (unsignedAttributes != null)
     {
         global::System.Collections.IEnumerator enumerator = unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken).GetEnumerator();
         try
         {
             while (enumerator.MoveNext())
             {
                 Attribute attribute = (Attribute)enumerator.get_Current();
                 {
                     global::System.Collections.IEnumerator enumerator2 = attribute.AttrValues.GetEnumerator();
                     try
                     {
                         while (enumerator2.MoveNext())
                         {
                             Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator2.get_Current();
                             try
                             {
                                 Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(asn1Encodable.ToAsn1Object());
                                 TimeStampToken     timeStampToken = new TimeStampToken(instance);
                                 TimeStampTokenInfo timeStampInfo  = timeStampToken.TimeStampInfo;
                                 byte[]             a = DigestUtilities.CalculateDigest(GetDigestAlgName(timeStampInfo.MessageImprintAlgOid), signerInfo.GetSignature());
                                 if (!Arrays.ConstantTimeAreEqual(a, timeStampInfo.GetMessageImprintDigest()))
                                 {
                                     throw new TspValidationException("Incorrect digest in message imprint");
                                 }
                                 list.Add((object)timeStampToken);
                             }
                             catch (SecurityUtilityException)
                             {
                                 throw new TspValidationException("Unknown hash algorithm specified in timestamp");
                             }
                             catch (global::System.Exception)
                             {
                                 throw new TspValidationException("Timestamp could not be parsed");
                             }
                         }
                     }
                     finally
                     {
                         global::System.IDisposable disposable2 = enumerator2 as global::System.IDisposable;
                         if (disposable2 != null)
                         {
                             disposable2.Dispose();
                         }
                     }
                 }
             }
             return((global::System.Collections.ICollection)list);
         }
         finally
         {
             global::System.IDisposable disposable = enumerator as global::System.IDisposable;
             if (disposable != null)
             {
                 disposable.Dispose();
             }
         }
     }
     return((global::System.Collections.ICollection)list);
 }
        /// <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);
        }
示例#43
0
 public TimeStampAndCrl(ContentInfo timeStamp)
 {
     this.timeStamp = timeStamp;
 }
示例#44
0
        /// <summary>
        /// Adds or removes Content to P7mFile
        /// </summary>
        /// <param name="CmsData">Signature Info</param>
        /// <param name="File">File, if null returns only Signature Info</param>
        /// <returns></returns>
        public static byte[] EmbedFileToPkcs(byte[] CmsData, byte[] File)
        {
            DerObjectIdentifier contentTypeOID = CmsObjectIdentifiers.Data;
            Asn1EncodableVector digestAlgs     = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos    = new Asn1EncodableVector();
            Asn1OctetString     octs           = null;

            if (File != null)
            {
                octs = new DerOctetString(File);
            }
            Org.BouncyCastle.Asn1.Cms.ContentInfo encInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(contentTypeOID, octs);

            CmsProcessable content = new CmsProcessableByteArray(CmsData);

            Asn1Set     certificates = null;
            Asn1Set     certrevlist  = null;
            ArrayList   _certs       = new ArrayList();
            ArrayList   _crls        = new ArrayList();
            ICollection certsColl    = new ArrayList();
            ICollection crlsColl     = new ArrayList();

            CmsSignedData          cms     = new CmsSignedData(CmsData);
            SignerInformationStore signers = cms.GetSignerInfos();
            IX509Store             store   = cms.GetCertificates("Collection");
            IX509Store             crls    = cms.GetCrls("Collection");

            certsColl = store.GetMatches(null);
            crlsColl  = crls.GetMatches(null);
            foreach (SignerInformation signer in signers.GetSigners())
            {
                //digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
                digestAlgs.Add(signer.DigestAlgorithmID);
                signerInfos.Add(signer.ToSignerInfo());
            }
            foreach (Org.BouncyCastle.X509.X509Certificate cert in certsColl)
            {
                _certs.Add(Asn1Object.FromByteArray(cert.GetEncoded()));
            }

            foreach (Org.BouncyCastle.X509.X509Certificate clr in crlsColl)
            {
                _crls.Add(Asn1Object.FromByteArray(clr.GetEncoded()));
            }

            if (_certs.Count != 0)
            {
                certificates = CreateBerSetFromList(_certs);
            }

            if (_crls.Count != 0)
            {
                certrevlist = CreateBerSetFromList(_crls);
            }

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(CmsObjectIdentifiers.SignedData, sd);
            byte[] retval = new CmsSignedData(content, contentInfo.GetDerEncoded()).GetEncoded();
            string asn    = BitConverter.ToString(retval).Replace("-", "");

            return(retval);
        }
        /**
         * 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 = UseDerForCerts
                    ?   CmsUtilities.CreateDerSetFromList(_certs)
                    :   CmsUtilities.CreateBerSetFromList(_certs);
            }

            Asn1Set certrevlist = null;

            if (_crls.Count != 0)
            {
                certrevlist = UseDerForCrls
                    ?   CmsUtilities.CreateDerSetFromList(_crls)
                    :   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 DerOctetString(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));
        }
示例#46
0
 public ScvpReqRes(ContentInfo request, ContentInfo response)
 {
     this.request = request;
     this.response = response;
 }
        /**
        * 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);
        }
示例#48
0
		public CmsSignedData(
			CmsProcessable  signedContent,
			ContentInfo     sigData)
		{
			this.signedContent = signedContent;
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);
		}