Beispiel #1
0
        public bool verify(AsymmetricKeyParameter key)
        {
            try {
                if (!this.isSigned())
                {
                    throw new OCSPException("attempt to verify signature on unsigned object");
                }

                // -------------------------------------------------------------
                Signer sig = SignerUtil.getSigner(this.getSignatureAlgOID());
                // The above may not work as not sure if key is dotted decimal oid as string or an ALG mechanism name.
                // -------------------------------------------------------------


                sig.init(false, key);

                MemoryStream     mStr = new MemoryStream();
                ASN1OutputStream aOut = new ASN1OutputStream(mStr);

                aOut.writeObject(req.getTbsRequest());

                byte[] b = mStr.ToArray();

                sig.update(b, 0, b.Length);

                return(sig.verifySignature(this.getSignature()));
            }
            catch (Exception e)
            {
                throw new OCSPException("exception processing sig: " + e, e);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Verify that requests' signature is valid.
        /// </summary>
        /// <param name="key">A public key to verify with.</param>
        /// <returns>true = verified.</returns>
        public bool verify(AsymmetricKeyParameter key)
        {
            Signer signer = SignerUtil.getSigner(new DERObjectIdentifier(this.getSignatureAlgOID()));

            signer.init(false, key);
            byte[] b = resp.getTbsResponseData().getEncoded();
            signer.update(b, 0, b.Length);
            return(signer.verifySignature(this.getSignature()));
        }
Beispiel #3
0
        /// <summary>
        /// Instanciate a PKCS10CertificationRequest object with the necessary credentials.
        /// </summary>
        ///<param name="signatureAlgorithm">Name of Sig Alg.</param>
        /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param>
        /// <param name="key">Public Key to be included in cert reqest.</param>
        /// <param name="attributes">ASN1Set of Attributes.</param>
        /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param>
        public PKCS10CertificationRequest(String signatureAlgorithm,
                                          X509Name subject,
                                          AsymmetricKeyParameter key,
                                          ASN1Set attributes,
                                          AsymmetricKeyParameter signingKey)

        {
            DERObjectIdentifier sigOID = SignerUtil.getObjectIdentifier(signatureAlgorithm.ToUpper());

            if (sigOID == null)
            {
                throw new ArgumentException("Unknown signature type requested");
            }

            if (subject == null)
            {
                throw new ArgumentException("subject must not be null");
            }

            if (key == null)
            {
                throw new ArgumentException("public key must not be null");
            }



            this.sigAlgId = new AlgorithmIdentifier(sigOID, null);

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);


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

            Signer sig = null;

            // Create appropriate Signature.
            sig = SignerUtil.getSigner(sigAlgId.getObjectId());

            sig.init(true, signingKey);

            // Encode.

            MemoryStream    mStr   = new MemoryStream();
            DEROutputStream derOut = new DEROutputStream(mStr);

            derOut.writeObject(reqInfo);

            // Sign
            byte[] b = mStr.ToArray();
            sig.update(b, 0, b.Length);

            // Generate Signature.
            sigBits = new DERBitString(sig.generateSignature());
        }
Beispiel #4
0
        /// <summary>
        /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
        /// <param name="random">The Secure Random you want to use.</param>
        /// <returns></returns>
        public X509CertificateStructure generateX509Certificate(
            AsymmetricKeyParameter privateKey,
            SecureRandom random)

        {
            Signer sig = null;

            try {
                sig = SignerUtil.getSigner(sigOID);
            }
            catch (Exception ex)
            {
                throw new Exception("exception creating signature: " + ex.Message);
            }

            if (random != null)
            {
                sig.init(true, privateKey);
            }
            else
            {
                sig.init(true, new ParametersWithRandom(privateKey, random));
            }

            TBSCertificateStructure tbsCert = tbsGen.generateTBSCertificate();

            try
            {
                MemoryStream    mStr = new MemoryStream();
                DEROutputStream dOut = new DEROutputStream(mStr);
                dOut.writeObject(tbsCert);
                mStr.Flush();
                byte[] b = mStr.ToArray();
                sig.update(b, 0, b.Length);
            }
            catch (Exception e)
            {
                throw new Exception("exception encoding TBS cert - " + e);
            }

            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(tbsCert);
            v.add(sigAlgId);
            v.add(new DERBitString(sig.generateSignature()));

            return(new X509CertificateStructure(new DERSequence(v)));
        }
Beispiel #5
0
        /// <summary>
        /// Verify PKCS10 Cert Reqest is valid.
        /// </summary>
        /// <returns>true = valid.</returns>
        public bool verify()
        {
            Signer sig = null;

            sig = SignerUtil.getSigner(sigAlgId.getObjectId());

            sig.init(false, getPublicKey());

            MemoryStream    mStr   = new MemoryStream();
            DEROutputStream derOut = new DEROutputStream(mStr);

            derOut.writeObject(reqInfo);
            derOut.Flush();
            byte[] b = mStr.ToArray();
            sig.update(b, 0, b.Length);
            mStr.Close();

            return(sig.verifySignature(sigBits.getBytes()));
        }
Beispiel #6
0
        /**
         * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
         * @param contentsKey the /Contents key
         * @param certsKey the /Cert key
         * @param provider the provider or <code>null</code> for the default provider
         * @throws SecurityException on error
         * @throws CRLException on error
         * @throws InvalidKeyException on error
         * @throws CertificateException on error
         * @throws NoSuchProviderException on error
         * @throws NoSuchAlgorithmException on error
         * @throws IOException on error
         */
        public PdfPKCS7(byte[] contentsKey, byte[] certsKey)
        {
            X509CertificateParser cf = new X509CertificateParser(certsKey);

            certs    = new ArrayList();
            signCert = cf.ReadCertificate();
            certs.Add(signCert);
            while (true)
            {
                X509Certificate cc = cf.ReadCertificate();
                if (cc == null)
                {
                    break;
                }
                certs.Add(cc);
            }
            crls = new ArrayList();
            ASN1InputStream inp = new ASN1InputStream(new MemoryStream(contentsKey));

            digest = ((DEROctetString)inp.readObject()).getOctets();
            sig    = SignerUtil.getSigner("SHA1withRSA");
            sig.init(false, signCert.getPublicKey());
        }
Beispiel #7
0
        /// <summary>
        /// Verify the certificates signature using the nominated public key.
        /// </summary>
        /// <param name="key">An appropriate public key parameter object, RSAPublicKeyParameters, DSAPublicKeyParameters or ECDSAPublicKeyParameters</param>
        /// <returns>True if the signature is valid.</returns>
        /// <exception cref="Exception">If key submitted is not of the above nomiated types.</exception>
        public bool verify(AsymmetricKeyParameter key)
        {
            Signer signature = null;

            try
            {
                signature = SignerUtil.getSigner(xStruct.getSignatureAlgorithm().getObjectId());
            }
            catch
            {
                throw new Exception("Signature not recognised.");
            }

            signature.init(false, key);
            byte[] b = this.getTBSCertificate();
            signature.update(b, 0, b.Length);

            if (!signature.verifySignature(this.getSignature()))
            {
                throw new Exception("Public key presented not for certificate signature");
            }
            return(true);
        }
Beispiel #8
0
        /**
         * Generates a signature.
         * @param privKey the private key
         * @param certChain the certificate chain
         * @param crlList the certificate revocation list
         * @param hashAlgorithm the hash algorithm
         * @param provider the provider or <code>null</code> for the default provider
         * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1
         * @throws SecurityException on error
         * @throws InvalidKeyException on error
         * @throws NoSuchProviderException on error
         * @throws NoSuchAlgorithmException on error
         */
        public PdfPKCS7(CipherParameters privKey, X509Certificate[] certChain, object[] crlList,
                        String hashAlgorithm, bool hasRSAdata)
        {
            this.privKey = privKey;

            if (hashAlgorithm.Equals("MD5"))
            {
                digestAlgorithm = ID_MD5;
            }
            else if (hashAlgorithm.Equals("MD2"))
            {
                digestAlgorithm = ID_MD2;
            }
            else if (hashAlgorithm.Equals("SHA"))
            {
                digestAlgorithm = ID_SHA1;
            }
            else if (hashAlgorithm.Equals("SHA1"))
            {
                digestAlgorithm = ID_SHA1;
            }
            else
            {
                throw new ArgumentException("Unknown Hash Algorithm " + hashAlgorithm);
            }

            version     = signerversion = 1;
            certs       = new ArrayList();
            crls        = new ArrayList();
            digestalgos = new Hashtable();
            digestalgos[digestAlgorithm] = null;

            //
            // Copy in the certificates and crls used to sign the private key.
            //
            signCert = certChain[0];
            for (int i = 0; i < certChain.Length; i++)
            {
                certs.Add(certChain[i]);
            }

//            if (crlList != null) {
//                for (int i = 0;i < crlList.length;i++) {
//                    crls.add(crlList[i]);
//                }
//            }

            if (privKey != null)
            {
                //
                // Now we have private key, find out what the digestEncryptionAlgorithm is.
                //
                if (privKey is RSAKeyParameters)
                {
                    digestEncryptionAlgorithm = ID_RSA;
                }
                else if (privKey is DSAKeyParameters)
                {
                    digestEncryptionAlgorithm = ID_DSA;
                }
                else
                {
                    throw new ArgumentException("Unknown Key Algorithm " + privKey.ToString());
                }
            }
            if (hasRSAdata)
            {
                RSAdata       = new byte[0];
                messageDigest = GetHashClass();
            }

            if (privKey != null)
            {
                sig = SignerUtil.getSigner(GetDigestAlgorithm());
                sig.init(true, privKey);
            }
        }
Beispiel #9
0
        /**
         * Verifies a signature using the sub-filter adbe.pkcs7.detached or
         * adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param provider the provider or <code>null</code> for the default provider
         * @throws SecurityException on error
         * @throws CRLException on error
         * @throws InvalidKeyException on error
         * @throws CertificateException on error
         * @throws NoSuchProviderException on error
         * @throws NoSuchAlgorithmException on error
         */
        public PdfPKCS7(byte[] contentsKey)
        {
            ASN1InputStream din = new ASN1InputStream(new MemoryStream(contentsKey));

            //
            // Basic checks to make sure it's a PKCS#7 SignedData Object
            //
            ASN1Object pkcs;

            try {
                pkcs = din.readObject();
            }
            catch  {
                throw new ArgumentException("can't decode PKCS7SignedData object");
            }
            if (!(pkcs is ASN1Sequence))
            {
                throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
            }
            ASN1Sequence        signedData = (ASN1Sequence)pkcs;
            DERObjectIdentifier objId      = (DERObjectIdentifier)signedData.getObjectAt(0);

            if (!objId.getId().Equals(ID_PKCS7_SIGNED_DATA))
            {
                throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
            }
            ASN1Sequence content = (ASN1Sequence)((DERTaggedObject)signedData.getObjectAt(1)).getObject();

            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

            // the version
            version = ((DERInteger)content.getObjectAt(0)).getValue().intValue();

            // the digestAlgorithms
            digestalgos = new Hashtable();
            IEnumerator e = ((ASN1Set)content.getObjectAt(1)).getObjects();

            while (e.MoveNext())
            {
                ASN1Sequence        s = (ASN1Sequence)e.Current;
                DERObjectIdentifier o = (DERObjectIdentifier)s.getObjectAt(0);
                digestalgos[o.getId()] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser(contentsKey);

            certs = new ArrayList();
            while (true)
            {
                X509Certificate cc = cf.ReadCertificate();
                if (cc == null)
                {
                    break;
                }
                certs.Add(cc);
            }
            crls = new ArrayList();

            // the possible ID_PKCS7_DATA
            ASN1Sequence rsaData = (ASN1Sequence)content.getObjectAt(2);

            if (rsaData.size() > 1)
            {
                DEROctetString rsaDataContent = (DEROctetString)((DERTaggedObject)rsaData.getObjectAt(1)).getObject();
                RSAdata = rsaDataContent.getOctets();
            }

            // the signerInfos
            int next = 3;

            while (content.getObjectAt(next) is DERTaggedObject)
            {
                ++next;
            }
            ASN1Set signerInfos = (ASN1Set)content.getObjectAt(next);

            if (signerInfos.size() != 1)
            {
                throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
            }
            ASN1Sequence signerInfo = (ASN1Sequence)signerInfos.getObjectAt(0);

            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DERInteger)signerInfo.getObjectAt(0)).getValue().intValue();
            // Get the signing certificate
            ASN1Sequence issuerAndSerialNumber = (ASN1Sequence)signerInfo.getObjectAt(1);
            BigInteger   serialNumber          = ((DERInteger)issuerAndSerialNumber.getObjectAt(1)).getValue();

            foreach (X509Certificate cert in certs)
            {
                if (serialNumber.Equals(cert.getSerialNumber()))
                {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null)
            {
                throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
            }
            digestAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(2)).getObjectAt(0)).getId();
            next            = 3;
            if (signerInfo.getObjectAt(next) is ASN1TaggedObject)
            {
                ASN1TaggedObject tagsig = (ASN1TaggedObject)signerInfo.getObjectAt(next);
                ASN1Sequence     sseq   = (ASN1Sequence)tagsig.getObject();
                MemoryStream     bOut   = new MemoryStream();
                ASN1OutputStream dout   = new ASN1OutputStream(bOut);
                try {
                    ASN1EncodableVector attribute = new ASN1EncodableVector();
                    for (int k = 0; k < sseq.size(); ++k)
                    {
                        attribute.add(sseq.getObjectAt(k));
                    }
                    dout.writeObject(new DERSet(attribute));
                    dout.Close();
                }
                catch (IOException) {}
                sigAttr = bOut.ToArray();

                for (int k = 0; k < sseq.size(); ++k)
                {
                    ASN1Sequence seq2 = (ASN1Sequence)sseq.getObjectAt(k);
                    if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().Equals(ID_MESSAGE_DIGEST))
                    {
                        ASN1Set sset = (ASN1Set)seq2.getObjectAt(1);
                        digestAttr = ((DEROctetString)sset.getObjectAt(0)).getOctets();
                        break;
                    }
                }
                if (digestAttr == null)
                {
                    throw new ArgumentException("Authenticated attribute is missing the digest.");
                }
                ++next;
            }
            digestEncryptionAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(next++)).getObjectAt(0)).getId();
            digest = ((DEROctetString)signerInfo.getObjectAt(next)).getOctets();
            if (RSAdata != null || digestAttr != null)
            {
                messageDigest = GetHashClass();
            }
            sig = SignerUtil.getSigner(GetDigestAlgorithm());
            sig.init(false, signCert.getPublicKey());
        }
Beispiel #10
0
/// <summary>
///
/// </summary>
/// <param name="signingAlgorithm">The OID of the signing algorithm.</param>
/// <param name="privkey">The signing private key.</param>
/// <param name="chain">An array containing X509Certificate objects, can be null.</param>
/// <param name="producedAt">The time this response is produced at.</param>
/// <param name="random">A SecureRandom instance.</param>
/// <returns></returns>
        public BasicOCSPResp generateResponse(
            DERObjectIdentifier signingAlgorithm,
            AsymmetricKeyParameter privkey,
            X509Certificate[]   chain,
            DateTime producedAt,
            SecureRandom random)
        {
            IEnumerator         it        = list.GetEnumerator();
            ASN1EncodableVector responses = new ASN1EncodableVector();

            while (it.MoveNext())
            {
                try
                {
                    responses.add(((ResponseObject)it.Current).toResponse());
                }
                catch (Exception e)
                {
                    throw new OCSPException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(new DERInteger(0), responderID.toASN1Object(), new DERGeneralizedTime(producedAt), new DERSequence(responses), responseExtensions);

            Signer sig = null;

            try
            {
                sig = SignerUtil.getSigner(signingAlgorithm);
                if (random != null)
                {
                    sig.init(true, new ParametersWithRandom(privkey, random));
                }
                else
                {
                    sig.init(true, privkey);
                }
            }
            catch (Exception e)
            {
                throw new OCSPException("exception creating signature: " + e, e);
            }

            DERBitString bitSig = null;

            try
            {
                MemoryStream    bOut = new MemoryStream();
                DEROutputStream dOut = new DEROutputStream(bOut);

                dOut.writeObject(tbsResp);
                byte[] b = bOut.ToArray();

                sig.update(b, 0, b.Length);
                bitSig = new DERBitString(sig.generateSignature());
            }
            catch (Exception e)
            {
                throw new OCSPException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, new DERNull());

            if (chain != null && chain.Length > 0)
            {
                ASN1EncodableVector v = new ASN1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.add(new X509CertificateStructure(
                                  (ASN1Sequence)makeObj(chain[i].getEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OCSPException("error processing certs", e);
                }


                return(new BasicOCSPResp(new BasicOCSPResponse(tbsResp, sigAlgId, bitSig, new DERSequence(v))));
            }
            else
            {
                return(new BasicOCSPResp(new BasicOCSPResponse(tbsResp, sigAlgId, bitSig, null)));
            }
        }
Beispiel #11
0
        private OCSPReq generateRequest(DERObjectIdentifier signingAlgorithm,
                                        AsymmetricKeyParameter key,
                                        X509Certificate[]   chain,
                                        SecureRandom random)

        {
            IEnumerator         it        = list.GetEnumerator();
            ASN1EncodableVector requests  = new ASN1EncodableVector();
            Signature           signature = null;

            while (it.MoveNext())
            {
                requests.add(((RequestObject)it.Current).toRequest());
            }


            TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions);

            Signer sig = null;

            if (signingAlgorithm != null)
            {
                try {
                    sig = SignerUtil.getSigner(signingAlgorithm.getId());

                    if (random != null)
                    {
                        sig.init(true, new ParametersWithRandom(key, random));
                    }
                    else
                    {
                        sig.init(true, key);
                    }
                }
                catch (Exception e)
                {
                    throw new OCSPException("exception creating signature: " + e.Message, e);
                }

                DERBitString bitSig = null;

                try
                {
                    MemoryStream     bOut = new MemoryStream();
                    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

                    aOut.writeObject(tbsReq);

                    byte[] b = bOut.ToArray();
                    sig.update(b, 0, b.Length);

                    bitSig = new DERBitString(sig.generateSignature());
                }
                catch (Exception e)
                {
                    throw new OCSPException("exception processing TBSRequest: " + e.Message, e);
                }

                AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, new DERNull());

                if (chain != null && chain.Length > 0)
                {
                    ASN1EncodableVector v = new ASN1EncodableVector();
                    try
                    {
                        for (int i = 0; i != chain.Length; i++)
                        {
                            v.add(new X509CertificateStructure((ASN1Sequence)makeObj(chain[i].getEncoded())));
                        }
                    }
                    catch (Exception e)
                    {
                        throw new OCSPException("error processing certs", e);
                    }

                    signature = new Signature(sigAlgId, bitSig, new DERSequence(v));
                }
                else
                {
                    signature = new Signature(sigAlgId, bitSig);
                }
            }

            return(new OCSPReq(new OCSPRequest(tbsReq, signature)));
        }
Beispiel #12
0
        /// <summary>
        /// Generate an X509Certificate using your own SecureRandom.
        /// </summary>
        /// <param name="key">The private key of the issuer that is signing this certificate.</param>
        /// <param name="random">You Secure Random instance.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate generateX509Certificate(AsymmetricKeyParameter key, SecureRandom random)
        {
            Signer sig = null;

            if (sigOID == null)
            {
                throw new Exception("no signature algorithm specified");
            }

            try
            {
                sig = SignerUtil.getSigner(sigOID);
            }
            catch
            {
                try
                {
                    sig = SignerUtil.getSigner(signatureAlgorithm);
                }
                catch (Exception e)
                {
                    throw new Exception("exception creating signature: " + e.Message);
                }
            }

            if (random != null)
            {
                sig.init(true, new ParametersWithRandom(key, random));
            }
            else
            {
                // Console.WriteLine("**" + sig.GetType());
                sig.init(true, key);
            }

            if (extensions != null)
            {
                tbsGen.setExtensions(new X509Extensions(extOrdering, extensions));
            }
            TBSCertificateStructure tbsCert = tbsGen.generateTBSCertificate();

            try
            {
                MemoryStream    mStr = new MemoryStream();
                DEROutputStream dOut = new DEROutputStream(mStr);
                dOut.writeObject(tbsCert);
                byte[] b = mStr.ToArray();
                sig.update(b, 0, b.Length);
            }
            catch (Exception e)
            {
                throw new Exception("exception encoding TBS cert - " + e);
            }
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(tbsCert);
            v.add(sigAlgId);
            v.add(new DERBitString(sig.generateSignature()));

            return(new X509Certificate(new DERSequence(v)));
        }