Exemple #1
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());
        }
Exemple #2
0
        ASN1Sequence decryptData(
            AlgorithmIdentifier algId,
            byte[]                data,
            char[]                password)
        {
            PKCS12PBEParams  pbeParams     = PKCS12PBEParams.getInstance(algId.getParameters());
            CipherParameters keyParameters = PBEUtil.generateCipherParameters(algId.getObjectId(), password, pbeParams);

            byte[] encoding = null;
            Object engine   = PBEUtil.createEngine(algId.getObjectId());

            if (engine is BufferedBlockCipher)
            {
                BufferedBlockCipher cipher = (BufferedBlockCipher)engine;

                cipher.init(false, keyParameters);

                int encLen = cipher.getOutputSize(data.Length);

                encoding = new byte[encLen];

                int off = cipher.processBytes(data, 0, data.Length, encoding, 0);

                cipher.doFinal(encoding, off);
            }
            else if (engine is StreamCipher)
            {
                StreamCipher cipher = (StreamCipher)engine;

                cipher.init(false, keyParameters);

                encoding = new byte[data.Length];

                cipher.processBytes(data, 0, data.Length, encoding, 0);
            }

            ASN1InputStream bIn = new ASN1InputStream(new MemoryStream(encoding));

            return((ASN1Sequence)bIn.readObject());
        }
Exemple #3
0
        /**
         * return true if the internal state represents the signature described
         * in the passed in array.
         */
        public bool verifySignature(byte[] signature)
        {
            if (forSigning)
            {
                throw (new Exception("RSADigestSignature not initialised for verification"));
            }

            byte[] hash = new byte[digest.getDigestSize()];

            digest.doFinal(hash, 0);

            DigestInfo digInfo;

            byte[] sig;

            sig     = rsaEngine.processBlock(signature, 0, signature.Length);
            digInfo = derDecode(sig);

            if (!digInfo.getAlgorithmId().getObjectId().Equals(algId.getObjectId()))
            {
                return(false);
            }


            if (!isNull(digInfo.getAlgorithmId().getParameters()))
            {
                return(false);
            }

            byte[] sigHash = digInfo.getDigest();

            if (hash.Length != sigHash.Length)
            {
                return(false);
            }

            for (int i = 0; i < hash.Length; i++)
            {
                if (sigHash[i] != hash[i])
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #4
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()));
        }
Exemple #5
0
        public static AsymmetricKeyParameter CreateKey(SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algId = keyInfo.getAlgorithmId();

            if (algId.getObjectId().Equals(PKCSObjectIdentifiers.rsaEncryption) ||
                algId.getObjectId().Equals(X509ObjectIdentifiers.id_ea_rsa))
            {
                RSAPublicKeyStructure pubKey = new RSAPublicKeyStructure((ASN1Sequence)keyInfo.getPublicKey());

                return(new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent()));
            }
            else if (algId.getObjectId().Equals(PKCSObjectIdentifiers.dhKeyAgreement) ||
                     algId.getObjectId().Equals(X9ObjectIdentifiers.dhpublicnumber))
            {
                DHParameter para = new DHParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger  derY = (DERInteger)keyInfo.getPublicKey();

                return(new DHPublicKeyParameters(derY.getValue(), new DHParameters(para.getP(), para.getG())));
            }
            else if (algId.getObjectId().Equals(OIWObjectIdentifiers.elGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger       derY = (DERInteger)keyInfo.getPublicKey();

                return(new ElGamalPublicKeyParameters(derY.getValue(), new ElGamalParameters(para.getP(), para.getG())));
            }
            else if (algId.getObjectId().Equals(X9ObjectIdentifiers.id_dsa) ||
                     algId.getObjectId().Equals(OIWObjectIdentifiers.dsaWithSHA1))
            {
                DSAParameter para = new DSAParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger   derY = (DERInteger)keyInfo.getPublicKey();

                return(new DSAPublicKeyParameters(derY.getValue(), new DSAParameters(para.getP(), para.getQ(), para.getG())));
            }
            else if (algId.getObjectId().Equals(X9ObjectIdentifiers.id_ecPublicKey))
            {
                X962Parameters     para    = new X962Parameters((ASN1Object)keyInfo.getAlgorithmId().getParameters());
                ECDomainParameters dParams = null;

                if (para.isNamedCurve())
                {
                    DERObjectIdentifier oid = (DERObjectIdentifier)para.getParameters();
                    X9ECParameters      ecP = X962NamedCurves.getByOID(oid);

                    dParams = new ECDomainParameters(
                        ecP.getCurve(),
                        ecP.getG(),
                        ecP.getN(),
                        ecP.getH(),
                        ecP.getSeed());
                }
                else
                {
                    X9ECParameters ecP = new X9ECParameters((ASN1Sequence)para.getParameters().toASN1Object());


                    dParams = new ECDomainParameters(
                        ecP.getCurve(),
                        ecP.getG(),
                        ecP.getN(),
                        ecP.getH(),
                        ecP.getSeed());
                }

                DERBitString    bits = keyInfo.getPublicKeyData();
                byte[]          data = bits.getBytes();
                ASN1OctetString key  = new DEROctetString(data);

                X9ECPoint derQ = new X9ECPoint(dParams.getCurve(), key);

                return(new ECPublicKeyParameters(derQ.getPoint(), dParams));
            }
            else
            {
                throw new Exception("algorithm identifier in key not recognised");
            }
        }
Exemple #6
0
        public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algId = keyInfo.getAlgorithmId();

            if (algId.getObjectId().Equals(PKCSObjectIdentifiers.rsaEncryption))
            {
                RSAPrivateKeyStructure keyStructure = new RSAPrivateKeyStructure((ASN1Sequence)keyInfo.getPrivateKey());
                return(new RSAPrivateCrtKeyParameters(
                           keyStructure.getModulus(),
                           keyStructure.getPublicExponent(),
                           keyStructure.getPrivateExponent(),
                           keyStructure.getPrime1(),
                           keyStructure.getPrime2(),
                           keyStructure.getExponent1(),
                           keyStructure.getExponent2(),
                           keyStructure.getCoefficient()));
            }
            else if (algId.getObjectId().Equals(PKCSObjectIdentifiers.dhKeyAgreement))
            {
                DHParameter para = new DHParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger  derX = (DERInteger)keyInfo.getPrivateKey();
                return(new DHPrivateKeyParameters(derX.getValue(), new DHParameters(para.getP(), para.getG())));
            }
            else if (algId.getObjectId().Equals(OIWObjectIdentifiers.elGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger       derX = (DERInteger)keyInfo.getPrivateKey();
                return(new ElGamalPrivateKeyParameters(derX.getValue(), new ElGamalParameters(para.getP(), para.getG())));
            }
            else if (algId.getObjectId().Equals(X9ObjectIdentifiers.id_dsa))
            {
                DSAParameter para = new DSAParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
                DERInteger   derX = (DERInteger)keyInfo.getPrivateKey();
                return(new DSAPrivateKeyParameters(derX.getValue(), new DSAParameters(para.getP(), para.getQ(), para.getG())));
            }
            else if (algId.getObjectId().Equals(X9ObjectIdentifiers.id_ecPublicKey))
            {
                X962Parameters     para    = new X962Parameters((ASN1Object)keyInfo.getAlgorithmId().getParameters());
                ECDomainParameters dParams = null;

                if (para.isNamedCurve())
                {
                    DERObjectIdentifier oid = (DERObjectIdentifier)para.getParameters();
                    X9ECParameters      ecP = X962NamedCurves.getByOID(oid);

                    dParams = new ECDomainParameters(
                        ecP.getCurve(),
                        ecP.getG(),
                        ecP.getN(),
                        ecP.getH(),
                        ecP.getSeed());
                }
                else
                {
                    X9ECParameters ecP = new X9ECParameters(
                        (ASN1Sequence)para.getParameters());
                    dParams = new ECDomainParameters(
                        ecP.getCurve(),
                        ecP.getG(),
                        ecP.getN(),
                        ecP.getH(),
                        ecP.getSeed());
                }

                ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence)keyInfo.getPrivateKey());

                return(new ECPrivateKeyParameters(ec.getKey(), dParams));
            }
            else
            {
                throw new Exception("algorithm identifier in key not recognised");
            }
        }
Exemple #7
0
        public PKCS12Store(
            Stream input,
            char[] password)
        {
            if (password == null)
            {
                throw new ArgumentException("No password supplied for PKCS12Store.");
            }

            ASN1InputStream bIn         = new ASN1InputStream(input);
            ASN1Sequence    obj         = (ASN1Sequence)bIn.readObject();
            Pfx             bag         = new Pfx(obj);
            ContentInfo     info        = bag.getAuthSafe();
            ArrayList       chain       = new ArrayList();
            bool            unmarkedKey = false;

            if (bag.getMacData() != null)           // check the mac code
            {
                MemoryStream        bOut   = new MemoryStream();
                BEROutputStream     berOut = new BEROutputStream(bOut);
                MacData             mData  = bag.getMacData();
                DigestInfo          dInfo  = mData.getMac();
                AlgorithmIdentifier algId  = dInfo.getAlgorithmId();
                byte[] salt    = mData.getSalt();
                int    itCount = mData.getIterationCount().intValue();

                berOut.writeObject(info);

                byte[] data = ((ASN1OctetString)info.getContent()).getOctets();

                try
                {
                    ASN1Encodable    parameters    = PBEUtil.generateAlgorithmParameters(algId.getObjectId(), mData.getSalt(), mData.getIterationCount().intValue());
                    CipherParameters keyParameters = PBEUtil.generateCipherParameters(algId.getObjectId(), password, parameters);
                    Mac mac = (Mac)PBEUtil.createEngine(algId.getObjectId());

                    mac.init(keyParameters);

                    mac.update(data, 0, data.Length);

                    byte[] res = new byte[mac.getMacSize()];

                    mac.doFinal(res, 0);

                    byte[] dig = dInfo.getDigest();

                    if (res.Length != dig.Length)
                    {
                        throw new Exception("PKCS12 key store mac invalid - wrong password or corrupted file.");
                    }

                    for (int i = 0; i != res.Length; i++)
                    {
                        if (res[i] != dig[i])
                        {
                            throw new Exception("PKCS12 key store mac invalid - wrong password or corrupted file.");
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("error constructing MAC: " + e.Message);
                }
            }

            keys     = new Hashtable();
            localIds = new Hashtable();

            if (info.getContentType().Equals(PKCSObjectIdentifiers.data))
            {
                bIn = new ASN1InputStream(new MemoryStream(((ASN1OctetString)info.getContent()).getOctets()));

                AuthenticatedSafe authSafe = new AuthenticatedSafe((ASN1Sequence)bIn.readObject());
                ContentInfo[]     c        = authSafe.getContentInfo();

                for (int i = 0; i != c.Length; i++)
                {
                    if (c[i].getContentType().Equals(PKCSObjectIdentifiers.data))
                    {
                        ASN1InputStream dIn = new ASN1InputStream(new MemoryStream(((ASN1OctetString)c[i].getContent()).getOctets()));
                        ASN1Sequence    seq = (ASN1Sequence)dIn.readObject();

                        for (int j = 0; j != seq.size(); j++)
                        {
                            SafeBag b = new SafeBag((ASN1Sequence)seq.getObjectAt(j));
                            if (b.getBagId().Equals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(password, eIn);
                                AsymmetricKeyParameter  privKey  = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                String             alias      = null;
                                ASN1OctetString    localId    = null;

                                if (b.getBagAttributes() != null)
                                {
                                    IEnumerator e = b.getBagAttributes().getObjects();
                                    while (e.MoveNext())
                                    {
                                        ASN1Sequence        sq      = (ASN1Sequence)e.Current;
                                        DERObjectIdentifier aOid    = (DERObjectIdentifier)sq.getObjectAt(0);
                                        ASN1Set             attrSet = (ASN1Set)sq.getObjectAt(1);
                                        ASN1Encodable       attr    = null;

                                        if (attrSet.size() > 0)
                                        {
                                            attr = attrSet.getObjectAt(0);

                                            attributes.Add(aOid.getId(), attr);
                                        }

                                        if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_friendlyName))
                                        {
                                            alias = ((DERBMPString)attr).getString();
                                            keys.Add(alias, pkcs12Key);
                                        }
                                        else if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId))
                                        {
                                            localId = (ASN1OctetString)attr;
                                        }
                                    }
                                }

                                if (localId != null)
                                {
                                    String name = byteArrayToString(Hex.encode(localId.getOctets()));

                                    if (alias == null)
                                    {
                                        keys.Add(name, pkcs12Key);
                                    }
                                    else
                                    {
                                        localIds.Add(alias, name);
                                    }
                                }
                                else
                                {
                                    unmarkedKey = true;
                                    keys.Add("unmarked", privKey);
                                }
                            }
                            else if (b.getBagId().Equals(PKCSObjectIdentifiers.certBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.getBagId());
                                Console.WriteLine("extra " + ASN1Dump.dumpAsString(b));
                            }
                        }
                    }
                    else if (c[i].getContentType().Equals(PKCSObjectIdentifiers.encryptedData))
                    {
                        EncryptedData d   = new EncryptedData((ASN1Sequence)c[i].getContent());
                        ASN1Sequence  seq = decryptData(d.getEncryptionAlgorithm(), d.getContent().getOctets(), password);

                        for (int j = 0; j != seq.size(); j++)
                        {
                            SafeBag b = new SafeBag((ASN1Sequence)seq.getObjectAt(j));

                            if (b.getBagId().Equals(PKCSObjectIdentifiers.certBag))
                            {
                                chain.Add(b);
                            }
                            else if (b.getBagId().Equals(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(password, eIn);
                                AsymmetricKeyParameter  privKey  = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                String             alias      = null;
                                ASN1OctetString    localId    = null;

                                IEnumerator e = b.getBagAttributes().getObjects();
                                while (e.MoveNext())
                                {
                                    ASN1Sequence        sq      = (ASN1Sequence)e.Current;
                                    DERObjectIdentifier aOid    = (DERObjectIdentifier)sq.getObjectAt(0);
                                    ASN1Set             attrSet = (ASN1Set)sq.getObjectAt(1);
                                    ASN1Encodable       attr    = null;

                                    if (attrSet.size() > 0)
                                    {
                                        attr = attrSet.getObjectAt(0);

                                        attributes.Add(aOid.getId(), attr);
                                    }

                                    if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_friendlyName))
                                    {
                                        alias = ((DERBMPString)attr).getString();
                                        keys.Add(alias, pkcs12Key);
                                    }
                                    else if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId))
                                    {
                                        localId = (ASN1OctetString)attr;
                                    }
                                }

                                String name = byteArrayToString(Hex.encode(localId.getOctets()));

                                if (alias == null)
                                {
                                    keys.Add(name, pkcs12Key);
                                }
                                else
                                {
                                    localIds.Add(alias, name);
                                }
                            }
                            else if (b.getBagId().Equals(PKCSObjectIdentifiers.keyBag))
                            {
                                PrivateKeyInfo         pIn     = PrivateKeyInfo.getInstance(b.getBagValue());
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(pIn);

                                //
                                // set the attributes on the key
                                //
                                String             alias      = null;
                                ASN1OctetString    localId    = null;
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);

                                IEnumerator e = b.getBagAttributes().getObjects();
                                while (e.MoveNext())
                                {
                                    ASN1Sequence        sq      = (ASN1Sequence)e.Current;
                                    DERObjectIdentifier aOid    = (DERObjectIdentifier)sq.getObjectAt(0);
                                    ASN1Set             attrSet = (ASN1Set)sq.getObjectAt(1);
                                    ASN1Encodable       attr    = null;

                                    if (attrSet.size() > 0)
                                    {
                                        attr = attrSet.getObjectAt(0);

                                        attributes.Add(aOid.getId(), attr);
                                    }

                                    if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_friendlyName))
                                    {
                                        alias = ((DERBMPString)attr).getString();
                                        keys.Add(alias, pkcs12Key);
                                    }
                                    else if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId))
                                    {
                                        localId = (ASN1OctetString)attr;
                                    }
                                }

                                String name = byteArrayToString(Hex.encode(localId.getOctets()));

                                if (alias == null)
                                {
                                    keys.Add(name, pkcs12Key);
                                }
                                else
                                {
                                    localIds.Add(alias, name);
                                }
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.getBagId());
                                Console.WriteLine("extra " + ASN1Dump.dumpAsString(b));
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("extra " + c[i].getContentType().getId());
                        Console.WriteLine("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
                    }
                }
            }

            certs      = new Hashtable();
            chainCerts = new Hashtable();
            keyCerts   = new Hashtable();

            for (int i = 0; i != chain.Count; i++)
            {
                SafeBag         b    = (SafeBag)chain[i];
                CertBag         cb   = new CertBag((ASN1Sequence)b.getBagValue());
                X509Certificate cert = new X509Certificate(((ASN1OctetString)cb.getCertValue()).getOctets());

                //
                // set the attributes
                //
                Hashtable            attributes = new Hashtable();
                X509CertificateEntry pkcs12cert = new X509CertificateEntry(cert, attributes);
                ASN1OctetString      localId    = null;
                String alias = null;

                if (b.getBagAttributes() != null)
                {
                    IEnumerator e = b.getBagAttributes().getObjects();
                    while (e.MoveNext())
                    {
                        ASN1Sequence        sq      = (ASN1Sequence)e.Current;
                        DERObjectIdentifier aOid    = (DERObjectIdentifier)sq.getObjectAt(0);
                        ASN1Set             attrSet = (ASN1Set)sq.getObjectAt(1);

                        if (attrSet.size() > 0)
                        {
                            ASN1Encodable attr = attrSet.getObjectAt(0);

                            attributes.Add(aOid.getId(), attr);

                            if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_friendlyName))
                            {
                                alias = ((DERBMPString)attr).getString();
                            }
                            else if (aOid.Equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId))
                            {
                                localId = (ASN1OctetString)attr;
                            }
                        }
                    }
                }

                chainCerts.Add(new CertId(cert.getPublicKey()), pkcs12cert);

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        String name = byteArrayToString(Hex.encode(new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cert.getPublicKey())).getKeyIdentifier()));

                        keyCerts.Add(name, pkcs12cert);
                        keys.Add(name, keys["unmarked"]);

                        keys.Remove("unmarked");
                    }
                }
                else
                {
                    if (alias == null)
                    {
                        if (localId != null)
                        {
                            String name = byteArrayToString(Hex.encode(localId.getOctets()));

                            keyCerts.Add(name, pkcs12cert);
                        }
                    }
                    else
                    {
                        certs.Add(alias, pkcs12cert);
                    }
                }
            }
        }