Exemplo n.º 1
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;
            }
        }
Exemplo n.º 2
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());
        }
        private byte[] CalculateSignature(IStreamCalculator signer, PkiHeader header, PkiBody body)
        {
            Asn1EncodableVector avec = new Asn1EncodableVector();

            avec.Add(header);
            avec.Add(body);
            byte[] encoded = new DerSequence(avec).GetEncoded();
            signer.Stream.Write(encoded, 0, encoded.Length);
            Object result = signer.GetResult();

            if (result is DefaultSignatureResult)
            {
                return(((DefaultSignatureResult)result).Collect());
            }
            else if (result is IBlockResult)
            {
                return(((IBlockResult)result).Collect());
            }
            else if (result is byte[])
            {
                return((byte[])result);
            }

            throw new InvalidOperationException("result is not byte[] or DefaultSignatureResult");
        }
        protected virtual void CheckSignature(
            IVerifierFactory verifier)
        {
            if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature))
            {
                throw new CertificateException("Signature algorithm in certificate info not same as outer certificate");
            }

            IStreamCalculator streamCalculator = verifier.CreateCalculator();

            try
            {
                byte[] b = this.cert.ACInfo.GetEncoded();

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

                Platform.Dispose(streamCalculator.Stream);
            }
            catch (IOException e)
            {
                throw new SignatureException("Exception encoding certificate info object", e);
            }

            if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
            {
                throw new InvalidKeyException("Public key presented not for certificate signature");
            }
        }
Exemplo n.º 6
0
        protected virtual void CheckSignature(IVerifierFactory verifier)
        {
            //IL_0063: Expected O, but got Unknown
            if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature))
            {
                throw new CertificateException("Signature algorithm in certificate info not same as outer certificate");
            }
            IStreamCalculator streamCalculator = verifier.CreateCalculator();

            try
            {
                byte[] encoded = cert.ACInfo.GetEncoded();
                streamCalculator.Stream.Write(encoded, 0, encoded.Length);
                Platform.Dispose(streamCalculator.Stream);
            }
            catch (IOException val)
            {
                IOException exception = val;
                throw new SignatureException("Exception encoding certificate info object", (global::System.Exception)(object) exception);
            }
            if (!((IVerifier)streamCalculator.GetResult()).IsVerified(GetSignature()))
            {
                throw new InvalidKeyException("Public key presented not for certificate signature");
            }
        }
Exemplo n.º 7
0
        /**
         * Initialise the signature object for verification.
         *
         * @param verifierBuilderProvider   provider for a content verifier builder for the signature type of interest.
         * @param pubKey  the public key to use for verification
         * @throws PgpException if there's an issue with creating the verifier.
         */
        public void InitVerify(IVerifierFactoryProvider <PgpSignatureTypeIdentifier> verifierFactoryProvider)
        {
            IVerifierFactory <PgpSignatureTypeIdentifier> verifierFactory = verifierFactoryProvider.CreateVerifierFactory(new PgpSignatureTypeIdentifier(sigPack.KeyAlgorithm, sigPack.HashAlgorithm));

            lastb  = 0;
            sigOut = verifierFactory.CreateCalculator();
        }
        public void CalculateSignatureShouldSucceed()
        {
            // The certificate should exist in the certificate store
            // on LocalMachine in CA store with appropriate subject CN
            // as it is defined in with the given "issuerSubject".
            // This certificate should have an associated private key that may not be exportable.
            const string issuerSubject = "L2";

            var privateKey = new PksEcPrivateKey(
                issuerSubject,
                "CA",
                "LocalMachine");

            const string algorithm = "SHA256withECDSA";

            ISignatureFactory signatureFactory = new PksAsn1SignatureFactory(algorithm, privateKey);

            // example of hash, real hash will be a longer byte array
            byte[] hash = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 };


            IStreamCalculator calculator = signatureFactory.CreateCalculator();

            using (var stream = calculator.Stream)
            {
                stream.Write(hash, 0, hash.Length);
            }

            object result = calculator.GetResult();

            byte[] signature = ((IBlockResult)result).Collect();  // ASN.1 DER formatted signature

            Assert.IsNotNull(signature);
        }
        /// <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);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Verify a message with a public key based signature attached.
        /// </summary>
        /// <param name="verifierFactory">a factory of signature verifiers.</param>
        /// <returns>true if the provider is able to create a verifier that validates the signature, false otherwise.</returns>
        public bool Verify(IVerifierFactory verifierFactory)
        {
            IStreamCalculator streamCalculator = verifierFactory.CreateCalculator();

            IVerifier result = (IVerifier)Process(streamCalculator);

            return(result.IsVerified(pkiMessage.Protection.GetBytes()));
        }
Exemplo n.º 11
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));
            }
Exemplo n.º 12
0
        /// <summary>Initialise the generator for signing.</summary>
        public void InitSign(
            int sigType,
            ISignatureWithDigestFactory <PgpSignatureIdentifier> signer)
        {
            this.signer        = signer.CreateCalculatorWithDigest();
            this.signatureId   = signer.AlgorithmDetails;
            this.signatureType = sigType;

            lastb = 0;
        }
        public ProtectedPkiMessage Build(IMacFactory factory)
        {
            IStreamCalculator calculator = factory.CreateCalculator();

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

            return(FinalizeMessage(header, protection));
        }
        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));
        }
Exemplo n.º 15
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()));
    }
        public byte[] CalculateFingerprint(PublicKeyPacket publicPk)
        {
            IBcpgKey key = publicPk.Key;

            if (publicPk.Version <= 3)
            {
                RsaPublicBcpgKey rK = (RsaPublicBcpgKey)key;

                try
                {
                    // TODO: MD5 needs to go in the main API...
                    MD5Digest digest = new MD5Digest();

                    byte[] bytes = new MPInteger(rK.Modulus).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    bytes = new MPInteger(rK.PublicExponent).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    byte[] digBuf = new byte[digest.GetDigestSize()];

                    digest.DoFinal(digBuf, 0);

                    return(digBuf);
                }
                catch (IOException e)
                {
                    throw new PgpException("can't encode key components: " + e.Message, e);
                }
            }
            else
            {
                try
                {
                    byte[] kBytes = publicPk.GetEncodedContents();

                    IStreamCalculator <IBlockResult> hashCalc = CryptoServicesRegistrar.CreateService(FipsShs.Sha1).CreateCalculator();
                    Stream hStream = hashCalc.Stream;

                    hStream.WriteByte((byte)0x99);
                    hStream.WriteByte((byte)(kBytes.Length >> 8));
                    hStream.WriteByte((byte)kBytes.Length);
                    hStream.Write(kBytes, 0, kBytes.Length);

                    hStream.Close();

                    return(hashCalc.GetResult().Collect());
                }
                catch (IOException e)
                {
                    throw new PgpException("can't encode key components: " + e.Message, e);
                }
            }
        }
        private static bool verify(IVerifierFactory verifier, AlgorithmIdentifier signatureAlgorithm, byte[] signedData, byte[] signature)
        {
            IStreamCalculator streamCalculator = verifier.CreateCalculator();

            byte[] b = signedData;

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

            //Platform.Dispose(streamCalculator.Stream);

            return(((IVerifier)streamCalculator.GetResult()).IsVerified(signature));
        }
Exemplo n.º 18
0
        internal static Stream attachDigestsToInputStream(ICollection digests, Stream s)
        {
            Stream      result = s;
            IEnumerator it     = digests.GetEnumerator();

            while (it.MoveNext())
            {
                IStreamCalculator <IBlockResult> digest = (IStreamCalculator <IBlockResult>)it.Current;
                result = new TeeInputStream(result, digest.Stream);
            }
            return(result);
        }
Exemplo n.º 19
0
        public Stream GetStream(Stream dataIn)
        {
            if (op is ICipherBuilder <AlgorithmIdentifier> )
            {
                return(((ICipherBuilder <AlgorithmIdentifier>)op).BuildCipher(dataIn).Stream);
            }
            else
            {
                macCalc = ((IMacFactory <AlgorithmIdentifier>)op).CreateCalculator();

                return(new TeeInputStream(dataIn, macCalc.Stream));
            }
        }
Exemplo n.º 20
0
        internal static MacData CreateMacData(IMacFactory <Pkcs12MacAlgDescriptor> macCalcFactory, byte[] data)
        {
            IStreamCalculator <IBlockResult> mdCalc = macCalcFactory.CreateCalculator();

            using (var str = mdCalc.Stream)
            {
                str.Write(data, 0, data.Length);
            }

            Pkcs12MacAlgDescriptor macAlg = macCalcFactory.AlgorithmDetails;

            return(new MacData(new DigestInfo(macAlg.DigestAlgorithm, mdCalc.GetResult().Collect()), macAlg.GetIV(), macAlg.IterationCount));
        }
    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());
    }
Exemplo n.º 22
0
        private object Process(IStreamCalculator streamCalculator)
        {
            Asn1EncodableVector avec = new Asn1EncodableVector();

            avec.Add(pkiMessage.Header);
            avec.Add(pkiMessage.Body);
            byte[] enc = new DerSequence(avec).GetDerEncoded();

            streamCalculator.Stream.Write(enc, 0, enc.Length);
            streamCalculator.Stream.Flush();
            streamCalculator.Stream.Close();

            return(streamCalculator.GetResult());
        }
        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));
        }
        public ProtectedPkiMessage Build(IMacFactory factory)
        {
            if (null == body)
            {
                throw new InvalidOperationException("body must be set before building");
            }

            IStreamCalculator calculator = factory.CreateCalculator();

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

            return(FinalizeMessage(header, protection));
        }
 public bool Verify(IVerifierFactory verifier)
 {
     try
     {
         byte[]            derEncoded       = reqInfo.GetDerEncoded();
         IStreamCalculator streamCalculator = verifier.CreateCalculator();
         streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
         Platform.Dispose(streamCalculator.Stream);
         return(((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetOctets()));
     }
     catch (Exception exception)
     {
         throw new SignatureException("exception encoding TBS cert request", exception);
     }
 }
        /// <summary>
        /// Generate a new X509Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculator">A signature calculator with the necessary algorithm details.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(ISignatureCalculator signatureCalculator)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculator.AlgorithmDetails);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

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

            streamCalculator.Stream.Close();

            return(GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).DoFinal()));
        }
Exemplo n.º 27
0
        protected virtual void CheckSignature(IVerifierFactory verifier)
        {
            if (!IsAlgIDEqual(this.c.SignatureAlgorithm, this.c.TbsCertificate.Signature))
            {
                throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
            }
            IStreamCalculator calculator = verifier.CreateCalculator();

            byte[] tbsCertificate = this.GetTbsCertificate();
            calculator.Stream.Write(tbsCertificate, 0, tbsCertificate.Length);
            Platform.Dispose(calculator.Stream);
            if (!((IVerifier)calculator.GetResult()).IsVerified(this.GetSignature()))
            {
                throw new InvalidKeyException("Public key presented not for certificate signature");
            }
        }
Exemplo n.º 28
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()));
        }
Exemplo n.º 29
0
        protected virtual void CheckSignature(IVerifierFactory verifier)
        {
            if (!this.c.SignatureAlgorithm.Equals(this.c.TbsCertList.Signature))
            {
                throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
            }
            IStreamCalculator calculator = verifier.CreateCalculator();

            byte[] tbsCertList = this.GetTbsCertList();
            calculator.Stream.Write(tbsCertList, 0, tbsCertList.Length);
            Platform.Dispose(calculator.Stream);
            if (!((IVerifier)calculator.GetResult()).IsVerified(this.GetSignature()))
            {
                throw new InvalidKeyException("CRL does not verify with supplied public key.");
            }
        }
        /// <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);
            }
        }