Ejemplo n.º 1
0
        public bool Verify()
        {
            byte[] trailer = GetSignatureTrailer();
            verifier.Stream.Write(trailer, 0, trailer.Length);

            return(verifier.GetResult().IsVerified(GetSignature()));
        }
        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");
            }
        }
        /// <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);
            }
        }
        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);
        }
Ejemplo n.º 5
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);
            }
        }
        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");
        }
Ejemplo n.º 7
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");
            }
        }
Ejemplo n.º 8
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));
        }
        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));
        }
    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());
    }
Ejemplo n.º 13
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));
        }
Ejemplo n.º 14
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 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);
     }
 }
Ejemplo n.º 16
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");
            }
        }
Ejemplo n.º 17
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.");
            }
        }
        public ProofOfPossessionSigningKeyBuilder setPublicKeyMac(PKMacBuilder generator, char[] password)
        {
            IMacFactory fact = generator.Build(password);

            IStreamCalculator calc = fact.CreateCalculator();

            byte[] d = _pubKeyInfo.GetDerEncoded();
            calc.Stream.Write(d, 0, d.Length);
            calc.Stream.Flush();
            calc.Stream.Close();

            this._publicKeyMAC = new PKMacValue(
                (AlgorithmIdentifier)fact.AlgorithmDetails,
                new DerBitString(((IBlockResult)calc.GetResult()).Collect()));

            return(this);
        }
        public ProofOfPossessionSigningKeyBuilder SetPublicKeyMac(PKMacBuilder generator, char[] password)
        {
            IMacFactory fact = generator.Build(password);

            IStreamCalculator calc = fact.CreateCalculator();

            byte[] d = _pubKeyInfo.GetDerEncoded();
            calc.Stream.Write(d, 0, d.Length);
            calc.Stream.Flush();
            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(calc.Stream);

            this._publicKeyMAC = new PKMacValue(
                (AlgorithmIdentifier)fact.AlgorithmDetails,
                new DerBitString(((IBlockResult)calc.GetResult()).Collect()));

            return(this);
        }
Ejemplo n.º 20
0
        /**
         * Verify the calculated signature against the passed in PgpSignature.
         *
         * @param pgpSig
         * @return boolean
         * @throws PgpException
         */
        public bool Verify(
            PgpSignature pgpSig)
        {
            try
            {
                byte[] trailer = pgpSig.GetSignatureTrailer();

                sigOut.Stream.Write(trailer, 0, trailer.Length);

                sigOut.Stream.Close();
            }
            catch (IOException e)
            {
                throw new PgpException("unable to add trailer: " + e.Message, e);
            }

            return(sigOut.GetResult().IsVerified(pgpSig.GetSignature()));
        }
Ejemplo n.º 21
0
        private void basicSha256Test(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            var sInfoGenerator = makeInfoGenerator(privateKey, cert, TspAlgorithms.Sha256, null, null);
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                sInfoGenerator,
                Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256), new DerObjectIdentifier("1.2"), true);


            tsTokenGen.SetCertificates(certs);

            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha256, new byte[32], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("23"), DateTime.Now);

            Assert.AreEqual((int)PkiStatus.Granted, tsResp.Status);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2]);

            Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256);
            IStreamCalculator calc    = digCalc.CreateCalculator();

            using (Stream s = calc.Stream)
            {
                var crt = cert.GetEncoded();
                s.Write(crt, 0, crt.Length);
            }

            byte[] certHash = ((SimpleBlockResult)calc.GetResult()).Collect();

            SigningCertificateV2 sigCertV2 = SigningCertificateV2.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]);

            Assert.IsTrue(Arrays.AreEqual(certHash, sigCertV2.GetCerts()[0].GetCertHash()));
        }
Ejemplo n.º 22
0
        public bool Verify(
            ISignatureVerifier verifier)
        {
            try
            {
                byte[] b = reqInfo.GetDerEncoded();

                IStreamCalculator streamCalculator = verifier.CreateCalculator();

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

                streamCalculator.Stream.Close();

                return(((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetBytes()));
            }
            catch (Exception e)
            {
                throw new SignatureException("exception encoding TBS cert request", e);
            }
        }
        public bool Verify(
            IVerifierFactory verifier)
        {
            try
            {
                byte[] b = reqInfo.GetDerEncoded();

                IStreamCalculator streamCalculator = verifier.CreateCalculator();

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

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

                return(((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetOctets()));
            }
            catch (Exception e)
            {
                throw new SignatureException("exception encoding TBS cert request", e);
            }
        }
        private byte[] calculateIdentifier(SubjectPublicKeyInfo publicKeyInfo)
        {
            byte[] bytes = publicKeyInfo.PublicKeyData.GetBytes();

            IStreamCalculator <IBlockResult> calculator = digestFactory.CreateCalculator();

            Stream cOut = calculator.Stream;

            try
            {
                cOut.Write(bytes, 0, bytes.Length);

                cOut.Close();
            }
            catch (IOException e)
            {   // it's hard to imagine this happening, but yes it does!
                throw new CertificateException("unable to calculate identifier: " + e.Message, e);
            }

            return(calculator.GetResult().Collect());
        }
Ejemplo n.º 25
0
        protected virtual void CheckSignature(
            IVerifierFactory verifier)
        {
            if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature))
            {
                throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
            }

            Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;

            IStreamCalculator streamCalculator = verifier.CreateCalculator();

            byte[] b = this.GetTbsCertificate();

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

            Platform.Dispose(streamCalculator.Stream);

            if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
            {
                throw new InvalidKeyException("Public key presented not for certificate signature");
            }
        }
        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);

            Platform.Dispose(streamCalculator.Stream);

            // Generate Signature.
            sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
        }
Ejemplo n.º 27
0
        protected virtual void CheckSignature(
            IVerifierFactory verifier)
        {
            if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
            {
                throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
            }

            //Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;

            IStreamCalculator streamCalculator = verifier.CreateCalculator();

            byte[] b = this.GetTbsCertList();

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

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

            if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
            {
                throw new InvalidKeyException("CRL does not verify with supplied public key.");
            }
        }
        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())));
        }
Ejemplo n.º 29
0
        private static byte[] checksum(IDigestFactory <PgpDigestTypeIdentifier> digCalcFactory, byte[] bytes, int length)
        {
            if (digCalcFactory != null)
            {
                IStreamCalculator <IBlockResult> digCalc = digCalcFactory.CreateCalculator();
                Stream dOut = digCalc.Stream;

                try
                {
                    dOut.Write(bytes, 0, length);

                    dOut.Close();
                }
                catch (Exception e)
                {
                    throw new PgpException("checksum digest calculation failed: " + e.Message, e);
                }
                return(digCalc.GetResult().Collect());
            }
            else
            {
                int checksum = 0;

                for (int i = 0; i != length; i++)
                {
                    checksum += bytes[i] & 0xff;
                }

                byte[] check = new byte[2];

                check[0] = (byte)(checksum >> 8);
                check[1] = (byte)checksum;

                return(check);
            }
        }
Ejemplo n.º 30
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);

            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()));
        }