Ejemplo n.º 1
0
        /// <summary>
        /// Generate a new X.509 Attribute Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An IX509AttributeCertificate.</returns>
        public IX509AttributeCertificate Generate(ISignatureFactory signatureCalculatorFactory)
        {
            if (!extGenerator.IsEmpty)
            {
                acInfoGen.SetExtensions(extGenerator.Generate());
            }

            AttributeCertificateInfo acInfo = acInfoGen.GenerateAttributeCertificateInfo();

            byte[] encoded = acInfo.GetDerEncoded();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(acInfo, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            try
            {
                v.Add(new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()));

                return(new X509V2AttributeCertificate(AttributeCertificate.GetInstance(new DerSequence(v))));
            }
            catch (Exception e)
            {
                // TODO
//				throw new ExtCertificateEncodingException("constructed invalid certificate", e);
                throw new CertificateEncodingException("constructed invalid certificate", e);
            }
        }
        //TODO: Abstract out common code to another method
        private async Task InitAsync(
            ISignatureFactory signatureFactory,
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes)
        {
            this.sigAlgId = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails;

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            IStreamCalculator streamCalculator = signatureFactory.CreateCalculator();

            byte[] reqInfoData = reqInfo.GetDerEncoded();

            streamCalculator.Stream.Write(reqInfoData, 0, reqInfoData.Length);

            Platform.Dispose(streamCalculator.Stream);

            // Generate Signature.
            var signedBits = await streamCalculator.GetResultAsync();

            sigBits = new DerBitString(((IBlockResult)signedBits).Collect());
        }
Ejemplo n.º 3
0
        internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory <AlgorithmIdentifier> signerFactory, IDigestFactoryProvider <AlgorithmIdentifier> digesterProvider, ISignatureEncryptionAlgorithmFinder sigEncAlgFinder, bool isDirectSignature)
        {
            this.sigId            = sigId;
            this.signer           = signerFactory;
            this.signerCalculator = signerFactory.CreateCalculator();

            if (digesterProvider != null)
            {
                this.digester         = digesterProvider.CreateDigestFactory(digAlgFinder.Find(signer.AlgorithmDetails));
                this.digestCalculator = digester.CreateCalculator();
            }
            else
            {
                this.digester = null;
            }

            this.sigEncAlgFinder = sigEncAlgFinder;

            this.isDirectSignature = isDirectSignature;
            if (this.isDirectSignature)
            {
                this.signedGen   = null;
                this.unsignedGen = null;
            }
            else
            {
                this.signedGen   = new DefaultSignedAttributeTableGenerator();
                this.unsignedGen = null;
            }
        }
        /// <summary>
        /// Generate a new X.509 Attribute Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An IX509AttributeCertificate.</returns>
        public IX509AttributeCertificate Generate(ISignatureFactory signatureCalculatorFactory)
        {
            if (!extGenerator.IsEmpty)
            {
                acInfoGen.SetExtensions(extGenerator.Generate());
            }

            AlgorithmIdentifier sigAlgID = (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails;

            acInfoGen.SetSignature(sigAlgID);

            AttributeCertificateInfo acInfo = acInfoGen.GenerateAttributeCertificateInfo();

            byte[] encoded = acInfo.GetDerEncoded();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);

            try
            {
                DerBitString signatureValue = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());

                return(new X509V2AttributeCertificate(new AttributeCertificate(acInfo, sigAlgID, signatureValue)));
            }
            catch (Exception e)
            {
                // TODO
//				throw new ExtCertificateEncodingException("constructed invalid certificate", e);
                throw new CertificateEncodingException("constructed invalid certificate", e);
            }
        }
Ejemplo n.º 5
0
            internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
            {
                //IL_00bf: Unknown result type (might be due to invalid IL or missing references)
                //IL_00c6: Expected O, but got Unknown
                AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID;
                string digestAlgName = Helper.GetDigestAlgName(digestOID);
                string algorithm     = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID);

                byte[] array;
                if (outer._digests.Contains((object)digestOID))
                {
                    array = (byte[])outer._digests.get_Item((object)digestOID);
                }
                else
                {
                    IDigest digestInstance = Helper.GetDigestInstance(digestAlgName);
                    content?.Write((Stream)(object)new DigOutputStream(digestInstance));
                    array = DigestUtilities.DoFinal(digestInstance);
                    outer._digests.Add((object)digestOID, ((global::System.Array)array).Clone());
                }
                IStreamCalculator streamCalculator = sigCalc.CreateCalculator();
                Stream            val     = (Stream) new BufferedStream(streamCalculator.Stream);
                Asn1Set           asn1Set = null;

                if (sAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters);
                    if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                    {
                        IDictionary val2 = attributeTable.ToDictionary();
                        val2.Remove((object)CmsAttributes.ContentType);
                        attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(val2);
                    }
                    asn1Set = outer.GetAttributeSet(attributeTable);
                    new DerOutputStream(val).WriteObject(asn1Set);
                }
                else
                {
                    content?.Write(val);
                }
                Platform.Dispose(val);
                byte[]  array2 = ((IBlockResult)streamCalculator.GetResult()).Collect();
                Asn1Set unauthenticatedAttributes = null;

                if (unsAttr != null)
                {
                    IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    baseParameters2.set_Item((object)CmsAttributeTableParameter.Signature, ((global::System.Array)array2).Clone());
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2);
                    unauthenticatedAttributes = outer.GetAttributeSet(attributes);
                }
                Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
                AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters);

                return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
            }
        internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
        {
            AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID;
            string digestAlgName = Helper.GetDigestAlgName(digestOID);
            string algorithm     = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID);

            byte[] array;
            if (outer._digests.Contains(digestOID))
            {
                array = (byte[])outer._digests[digestOID];
            }
            else
            {
                IDigest digestInstance = Helper.GetDigestInstance(digestAlgName);
                content?.Write(new DigOutputStream(digestInstance));
                array = DigestUtilities.DoFinal(digestInstance);
                outer._digests.Add(digestOID, array.Clone());
            }
            IStreamCalculator streamCalculator = sigCalc.CreateCalculator();
            Stream            stream           = new BufferedStream(streamCalculator.Stream);
            Asn1Set           asn1Set          = null;

            if (sAttr != null)
            {
                IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters);
                if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                {
                    IDictionary dictionary = attributeTable.ToDictionary();
                    dictionary.Remove(CmsAttributes.ContentType);
                    attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                }
                asn1Set = outer.GetAttributeSet(attributeTable);
                new DerOutputStream(stream).WriteObject(asn1Set);
            }
            else
            {
                content?.Write(stream);
            }
            Platform.Dispose(stream);
            byte[]  array2 = ((IBlockResult)streamCalculator.GetResult()).Collect();
            Asn1Set unauthenticatedAttributes = null;

            if (unsAttr != null)
            {
                IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2);
                unauthenticatedAttributes = outer.GetAttributeSet(attributes);
            }
            Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
            AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters);

            return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
        }
Ejemplo n.º 7
0
    public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
    {
        tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);
        TbsCertificateStructure tbsCertificateStructure = tbsGen.GenerateTbsCertificate();
        IStreamCalculator       streamCalculator        = signatureCalculatorFactory.CreateCalculator();

        byte[] derEncoded = tbsCertificateStructure.GetDerEncoded();
        streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
        Platform.Dispose(streamCalculator.Stream);
        return(GenerateJcaObject(tbsCertificateStructure, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
    }
    private void init(ISignatureFactory signatureCalculator, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey)
    {
        sigAlgId = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
        SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

        reqInfo = new CertificationRequestInfo(subject, pkInfo, attributes);
        IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

        byte[] derEncoded = reqInfo.GetDerEncoded();
        streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
        Platform.Dispose(streamCalculator.Stream);
        sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
    }
        public ProtectedPkiMessage Build(ISignatureFactory signatureFactory)
        {
            IStreamCalculator calculator = signatureFactory.CreateCalculator();

            if (!(signatureFactory.AlgorithmDetails is AlgorithmIdentifier))
            {
                throw new ArgumentException("AlgorithmDetails is not AlgorithmIdentifier");
            }

            FinalizeHeader((AlgorithmIdentifier)signatureFactory.AlgorithmDetails);
            PkiHeader    header     = hdrBuilBuilder.Build();
            DerBitString protection = new DerBitString(CalculateSignature(calculator, header, body));

            return(FinalizeMessage(header, protection));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Generate a new X509CRL using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509CRL.</returns>
        public X509Crl Generate(ISignatureFactory <AlgorithmIdentifier> signatureCalculatorFactory)
        {
            tbsGen.SetSignature(signatureCalculatorFactory.AlgorithmDetails);

            TbsCertificateList tbsCertList = GenerateCertList();

            Crypto.IStreamCalculator <IBlockResult> streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCertList.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return(GenerateJcaObject(tbsCertList, signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generate a new X509Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);

            return(GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
        }
        /// <summary>
        /// Generate an PKCS#10 request based on the past in signer.
        /// </summary>
        /// <param name="signerFactory">the content signer to be used to generate the signature validating the certificate.</param>
        /// <returns>a holder containing the resulting PKCS#10 certification request.</returns>
        public Pkcs10CertificationRequest Build(
            ISignatureFactory <AlgorithmIdentifier> signerFactory)
        {
            CertificationRequestInfo info;

            if (attributes.Count == 0)
            {
                if (leaveOffEmpty)
                {
                    info = new CertificationRequestInfo(subject, publicKeyInfo, null);
                }
                else
                {
                    info = new CertificationRequestInfo(subject, publicKeyInfo, new DerSet());
                }
            }
            else
            {
                Asn1EncodableVector v = new Asn1EncodableVector();

                for (int i = 0; i != attributes.Count; i++)
                {
                    v.Add(AttributePkcs.GetInstance(attributes[i]));
                }

                info = new CertificationRequestInfo(subject, publicKeyInfo, new DerSet(v));
            }

            try
            {
                IStreamCalculator <IBlockResult> signer = signerFactory.CreateCalculator();

                Stream sOut = signer.Stream;

                byte[] data = info.GetEncoded(Asn1Encodable.Der);

                sOut.Write(data, 0, data.Length);

                sOut.Close();

                return(new Pkcs10CertificationRequest(new CertificationRequest(info, signerFactory.AlgorithmDetails, new DerBitString(signer.GetResult().Collect()))));
            }
            catch (IOException e)
            {
                throw new InvalidOperationException("cannot produce certification request signature: " + e.Message, e);
            }
        }
Ejemplo n.º 13
0
 internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory <AlgorithmIdentifier> contentSigner, IDigestFactoryProvider <AlgorithmIdentifier> digesterProvider, ISignatureEncryptionAlgorithmFinder sigEncAlgFinder, ICmsAttributeTableGenerator signedGen, ICmsAttributeTableGenerator unsignedGen)
 {
     this.sigId            = sigId;
     this.signer           = contentSigner;
     this.signerCalculator = contentSigner.CreateCalculator();
     if (digesterProvider != null)
     {
         this.digester         = digesterProvider.CreateDigestFactory(digAlgFinder.Find(signer.AlgorithmDetails));
         this.digestCalculator = digester.CreateCalculator();
     }
     else
     {
         this.digester = null;
     }
     this.sigEncAlgFinder   = sigEncAlgFinder;
     this.signedGen         = signedGen;
     this.unsignedGen       = unsignedGen;
     this.isDirectSignature = false;
 }
        /// <summary>
        /// Generate a new X509Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(ISignatureFactory <AlgorithmIdentifier> signatureCalculatorFactory)
        {
            tbsGen.SetSignature(signatureCalculatorFactory.AlgorithmDetails);

            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator <IBlockResult> streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return(GenerateJcaObject(tbsCert, signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
        }
        // TODO: Abstract out common code to another method
        /// <summary>
        /// Generate a new X509Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509Certificate.</returns>
        public async Task <X509Certificate> GenerateAsync(ISignatureFactory signatureCalculatorFactory)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            var signedBits = await streamCalculator.GetResultAsync();

            return(GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)signedBits).Collect()));
        }
        private void Init(
            ISignatureFactory signatureFactory,
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes)
        {
            this.sigAlgId = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails;

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            IStreamCalculator streamCalculator = signatureFactory.CreateCalculator();

            byte[] reqInfoData = reqInfo.GetDerEncoded();

            streamCalculator.Stream.Write(reqInfoData, 0, reqInfoData.Length);

            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);

            // Generate Signature.
            sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
        }
        public PopoSigningKey Build(ISignatureFactory signer)
        {
            if (_name != null && _publicKeyMAC != null)
            {
                throw new InvalidOperationException("name and publicKeyMAC cannot both be set.");
            }

            PopoSigningKeyInput popo;

            byte[]            b;
            IStreamCalculator calc = signer.CreateCalculator();

            if (_certRequest != null)
            {
                popo = null;
                b    = _certRequest.GetDerEncoded();
                calc.Stream.Write(b, 0, b.Length);
            }
            else if (_name != null)
            {
                popo = new PopoSigningKeyInput(_name, _pubKeyInfo);
                b    = popo.GetDerEncoded();
                calc.Stream.Write(b, 0, b.Length);
            }
            else
            {
                popo = new PopoSigningKeyInput(_publicKeyMAC, _pubKeyInfo);
                b    = popo.GetDerEncoded();
                calc.Stream.Write(b, 0, b.Length);
            }

            calc.Stream.Flush();
            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(calc.Stream);
            DefaultSignatureResult res = (DefaultSignatureResult)calc.GetResult();

            return(new PopoSigningKey(popo, (AlgorithmIdentifier)signer.AlgorithmDetails, new DerBitString(res.Collect())));
        }
 internal SigWithDigest(ISignatureFactory <IParameters <Algorithm> > sigFact, IDigestFactory <IParameters <Algorithm> > digFact)
 {
     this.sigCalc     = sigFact.CreateCalculator();
     this.digCalc     = digFact.CreateCalculator();
     this.jointStream = new TeeOutputStream(sigCalc.Stream, digCalc.Stream);
 }
		/// <summary>
		/// Generate a new X509Certificate using the passed in SignatureCalculator.
		/// </summary>
		/// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
		/// <returns>An X509Certificate.</returns>
		public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
		{
			tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

			IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

			byte[] encoded = tbsCert.GetDerEncoded();

			streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
		}
        private BasicOcspResp GenerateResponse(ISignatureFactory signatureCalculator, X509Certificate[] chain, global::System.DateTime producedAt)
        {
            //IL_016c: Expected O, but got Unknown
            AlgorithmIdentifier algorithmIdentifier = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier algorithm           = algorithmIdentifier.Algorithm;
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)list).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    ResponseObject responseObject = (ResponseObject)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(responseObject.ToResponse());
                    }
                    catch (global::System.Exception e)
                    {
                        throw new OcspException("exception creating Request", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            ResponseData responseData = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(asn1EncodableVector), responseExtensions);
            DerBitString derBitString = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();
                byte[]            derEncoded       = responseData.GetDerEncoded();
                streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
                Platform.Dispose(streamCalculator.Stream);
                derBitString = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (global::System.Exception ex)
            {
                throw new OcspException(string.Concat((object)"exception processing TBSRequest: ", (object)ex), ex);
            }
            AlgorithmIdentifier sigAlgID = OcspUtilities.GetSigAlgID(algorithm);
            DerSequence         certs    = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        asn1EncodableVector2.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException val)
                {
                    IOException e2 = val;
                    throw new OcspException("error processing certs", (global::System.Exception)(object) e2);
                }
                catch (CertificateEncodingException e3)
                {
                    throw new OcspException("error encoding certs", e3);
                }
                certs = new DerSequence(asn1EncodableVector2);
            }
            return(new BasicOcspResp(new BasicOcspResponse(responseData, sigAlgID, derBitString, certs)));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Generate a new X509Crl using the passed in SignatureCalculator.
        /// </summary>
		/// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509Crl.</returns>
        public X509Crl Generate(ISignatureFactory signatureCalculatorFactory)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            TbsCertificateList tbsCertList = GenerateCertList();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCertList.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return GenerateJcaObject(tbsCertList, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
        }
		private BasicOcspResp GenerateResponse(
			ISignatureFactory    signatureCalculator,
			X509Certificate[]		chain,
			DateTime				producedAt)
		{
            AlgorithmIdentifier signingAlgID = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

			Asn1EncodableVector responses = new Asn1EncodableVector();

			foreach (ResponseObject respObj in list)
			{
				try
				{
					responses.Add(respObj.ToResponse());
				}
				catch (Exception e)
				{
					throw new OcspException("exception creating Request", e);
				}
			}

			ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
			DerBitString bitSig = null;

			try
			{
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

				byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                Platform.Dispose(streamCalculator.Stream);

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
			}
			catch (Exception e)
			{
				throw new OcspException("exception processing TBSRequest: " + e, e);
			}

			AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

			DerSequence chainSeq = null;
			if (chain != null && chain.Length > 0)
			{
				Asn1EncodableVector v = new Asn1EncodableVector();
				try
				{
					for (int i = 0; i != chain.Length; i++)
					{
						v.Add(
							X509CertificateStructure.GetInstance(
								Asn1Object.FromByteArray(chain[i].GetEncoded())));
					}
				}
				catch (IOException e)
				{
					throw new OcspException("error processing certs", e);
				}
				catch (CertificateEncodingException e)
				{
					throw new OcspException("error encoding certs", e);
				}

				chainSeq = new DerSequence(v);
			}

			return new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq));
		}
Ejemplo n.º 23
0
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType,
                CmsProcessable content,
                SecureRandom random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
                string digestName            = Helper.GetDigestAlgName(digestOID);

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);

                byte[] hash;
                if (outer._digests.Contains(digestOID))
                {
                    hash = (byte[])outer._digests[digestOID];
                }
                else
                {
                    IDigest dig = Helper.GetDigestInstance(digestName);
                    if (content != null)
                    {
                        content.Write(new DigOutputStream(dig));
                    }
                    hash = DigestUtilities.DoFinal(dig);
                    outer._digests.Add(digestOID, hash.Clone());
                }

                IStreamCalculator calculator = sigCalc.CreateCalculator();

#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE
                Stream sigStr = calculator.Stream;
#else
                Stream sigStr = new BufferedStream(calculator.Stream);
#endif

                Asn1Set signedAttr = null;
                if (sAttr != null)
                {
                    IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                    AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (contentType == null) //counter signature
                    {
                        if (signed != null && signed[CmsAttributes.ContentType] != null)
                        {
                            IDictionary tmpSigned = signed.ToDictionary();
                            tmpSigned.Remove(CmsAttributes.ContentType);
                            signed = new AttributeTable(tmpSigned);
                        }
                    }

                    // TODO Validate proposed signed attributes

                    signedAttr = outer.GetAttributeSet(signed);

                    // sig must be composed from the DER encoding.
                    new DerOutputStream(sigStr).WriteObject(signedAttr);
                }
                else if (content != null)
                {
                    // TODO Use raw signature of the hash value instead
                    content.Write(sigStr);
                }

                Platform.Dispose(sigStr);
                byte[] sigBytes = ((IBlockResult)calculator.GetResult()).Collect();

                Asn1Set unsignedAttr = null;
                if (unsAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                    baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
                    AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

                    // TODO Validate proposed unsigned attributes

                    unsignedAttr = outer.GetAttributeSet(unsigned);
                }

                // TODO[RSAPSS] Need the ability to specify non-default parameters
                Asn1Encodable       sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
                AlgorithmIdentifier encAlgId          = Helper.GetEncAlgorithmIdentifier(
                    new DerObjectIdentifier(encOID), sigX509Parameters);

                return(new SignerInfo(signerIdentifier, digAlgId,
                                      signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr));
            }
Ejemplo n.º 24
0
        private BasicOcspResp GenerateResponse(
            ISignatureFactory signatureCalculator,
            X509Certificate[]               chain,
            DateTime producedAt)
        {
            AlgorithmIdentifier signingAlgID     = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
            DerBitString bitSig  = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

                byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                Platform.Dispose(streamCalculator.Stream);

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq)));
        }
        private void init(
            ISignatureFactory signatureCalculator, 
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            AsymmetricKeyParameter signingKey)
        {
            this.sigAlgId = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

            byte[] reqInfoData = reqInfo.GetDerEncoded();

            streamCalculator.Stream.Write(reqInfoData, 0, reqInfoData.Length);

            Platform.Dispose(streamCalculator.Stream);

            // Generate Signature.
            sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
        }
        /// <summary>
        /// Generate a new X.509 Attribute Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An IX509AttributeCertificate.</returns>
        public IX509AttributeCertificate Generate(ISignatureFactory signatureCalculatorFactory)
        {
            if (!extGenerator.IsEmpty)
			{
				acInfoGen.SetExtensions(extGenerator.Generate());
			}

			AttributeCertificateInfo acInfo = acInfoGen.GenerateAttributeCertificateInfo();

            byte[] encoded = acInfo.GetDerEncoded();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            Asn1EncodableVector v = new Asn1EncodableVector();

			v.Add(acInfo, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

			try
			{
				v.Add(new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()));

				return new X509V2AttributeCertificate(AttributeCertificate.GetInstance(new DerSequence(v)));
			}
			catch (Exception e)
			{
				// TODO
//				throw new ExtCertificateEncodingException("constructed invalid certificate", e);
				throw new CertificateEncodingException("constructed invalid certificate", e);
			}
		}
Ejemplo n.º 27
0
 public IStreamCalculator <IBlockResult> CreateCalculator()
 {
     return(baseFactory.CreateCalculator());
 }