⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 certtools.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
        Security.removeProvider("BC");    	    }    public static synchronized void installBCProvider() {        // A flag that ensures that we intall the parameters for implcitlyCA only when we have installed a new provider        boolean installImplicitlyCA = false;        if (Security.addProvider(new BouncyCastleProvider()) < 0) {            // If already installed, remove so we can handle redeploy            // Nope, we ignore re-deploy on this level, because it can happen            // that the BC-provider is uninstalled, in just the second another            // thread tries to use the provider, and then that request will fail.            if (developmentProviderInstallation) {                removeBCProvider();                if (Security.addProvider(new BouncyCastleProvider()) < 0) {                    log.error("Cannot even install BC provider again!");                } else {                    installImplicitlyCA = true;                }            }        } else {            installImplicitlyCA = true;        }        if (installImplicitlyCA) {            // Install EC parameters for implicitlyCA encoding of EC keys, we have default curve parameters if no new ones have been given.            // The parameters are only used if implicitlyCA is used for generating keys, or verifying certs            checkImplicitParams();            ECCurve curve = new ECCurve.Fp(                    new BigInteger(IMPLICITLYCA_Q), // q                    new BigInteger(IMPLICITLYCA_A, 16), // a                    new BigInteger(IMPLICITLYCA_B, 16)); // b            org.bouncycastle.jce.spec.ECParameterSpec implicitSpec = new org.bouncycastle.jce.spec.ECParameterSpec(                    curve,                    curve.decodePoint(Hex.decode(IMPLICITLYCA_G)), // G                    new BigInteger(IMPLICITLYCA_N)); // n            ConfigurableProvider config = (ConfigurableProvider)Security.getProvider("BC");            if (config != null) {                config.setParameter(ConfigurableProvider.EC_IMPLICITLY_CA, implicitSpec);                                                           } else {                log.error("Can not get ConfigurableProvider, implicitlyCA EC parameters NOT set!");            }                        }                // 2007-05-25        // Finally we must configure SERIALNUMBER behaviour in BC >=1.36 to be the same        // as the behaviour in BC 1.35, it changed from SN to SERIALNUMBER in BC 1.36        // We must be backwards compatible        X509Name.DefaultSymbols.put(X509Name.SN, "SN");    }    /** Check if parameters have been set correctly during pre-process, otherwise log an error and     * set default values. Mostly used to be able to do JUnit testing     */    private static void checkImplicitParams() {        if (StringUtils.contains(IMPLICITLYCA_Q, "ecdsa.implicitlyca.q")) {        	log.error("IMPLICITLYCA_Q not set!");        	IMPLICITLYCA_Q = "883423532389192164791648750360308885314476597252960362792450860609699839";        }        if (StringUtils.contains(IMPLICITLYCA_A, "ecdsa.implicitlyca.a")) {        	log.error("IMPLICITLYCA_A not set!");        	IMPLICITLYCA_A = "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc";        }        if (StringUtils.contains(IMPLICITLYCA_B, "ecdsa.implicitlyca.b")) {        	log.error("IMPLICITLYCA_B not set!");        	IMPLICITLYCA_B = "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a";        }        if (StringUtils.contains(IMPLICITLYCA_G, "ecdsa.implicitlyca.g")) {        	log.error("IMPLICITLYCA_G not set!");        	IMPLICITLYCA_G = "020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf";        }        if (StringUtils.contains(IMPLICITLYCA_N, "ecdsa.implicitlyca.n")) {        	log.error("IMPLICITLYCA_N not set!");        	IMPLICITLYCA_N = "883423532389192164791648750360308884807550341691627752275345424702807307";        }    }        /**     * Reads a certificate in PEM-format from a file. The file may contain other things,     * the first certificate in the file is read.     *     * @param certFile the file containing the certificate in PEM-format     * @return Ordered Collection of X509Certificate, first certificate first, or empty Collection     * @exception IOException if the filen cannot be read.     * @exception CertificateException if the filen does not contain a correct certificate.     */    public static Collection getCertsFromPEM(String certFile) throws IOException, CertificateException {        log.debug(">getCertfromPEM: certFile=" + certFile);        InputStream inStrm = null;        Collection certs;		try {			inStrm = new FileInputStream(certFile);			certs = getCertsFromPEM(inStrm);		} finally {			if (inStrm != null) inStrm.close();		}        log.debug("<getCertfromPEM: certFile=" + certFile);        return certs;    }    /**     * Reads a certificate in PEM-format from an InputStream. The stream may contain other things,     * the first certificate in the stream is read.     *     * @param certFile the input stream containing the certificate in PEM-format     * @return Ordered Collection of X509Certificate, first certificate first, or empty Collection     * @exception IOException if the stream cannot be read.     * @exception CertificateException if the stream does not contain a correct certificate.     */    public static Collection getCertsFromPEM(InputStream certstream)    throws IOException, CertificateException {        log.debug(">getCertfromPEM:");        ArrayList ret = new ArrayList();        String beginKey = "-----BEGIN CERTIFICATE-----";        String endKey = "-----END CERTIFICATE-----";        BufferedReader bufRdr = null;        ByteArrayOutputStream ostr = null;        PrintStream opstr = null;		try {			bufRdr = new BufferedReader(new InputStreamReader(certstream));			while (bufRdr.ready()) {				ostr = new ByteArrayOutputStream();				opstr = new PrintStream(ostr);				String temp;				while ((temp = bufRdr.readLine()) != null						&& !temp.equals(beginKey))					continue;				if (temp == null)					throw new IOException("Error in " + certstream.toString()							+ ", missing " + beginKey + " boundary");				while ((temp = bufRdr.readLine()) != null						&& !temp.equals(endKey))					opstr.print(temp);				if (temp == null)					throw new IOException("Error in " + certstream.toString()							+ ", missing " + endKey + " boundary");				opstr.close();				byte[] certbuf = Base64.decode(ostr.toByteArray());				ostr.close();				// Phweeew, were done, now decode the cert from file back to X509Certificate object				CertificateFactory cf = CertTools.getCertificateFactory();				X509Certificate x509cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certbuf));				ret.add(x509cert);			}		} finally {			if (bufRdr != null) bufRdr.close();			if (opstr != null) opstr.close();			if (ostr != null) ostr.close();		}        		log.debug("<getcertfromPEM:" + ret.size());        return ret;    } // getCertsFromPEM   /** Converts a regular array of certificates into an ArrayList, using the provided provided.    *     * @param certs Certificate[] of certificates to convert    * @param provider provider for example "SUN" or "BC", use null for the default provider (BC)    * @return An ArrayList of certificates in the same order as the passed in array    * @throws NoSuchProviderException     * @throws CertificateException     */    public static ArrayList getCertCollectionFromArray(Certificate[] certs, String provider) throws CertificateException, NoSuchProviderException {    	log.debug(">getCertCollectionFromArray: "+provider);    	ArrayList ret = new ArrayList();    	String prov = provider;    	if (prov == null) {    		prov = "BC";    	}    	for (int i=0; i < certs.length; i++) {    		CertificateFactory cf = CertificateFactory.getInstance("X.509", prov);    		Certificate cert = certs[i];    		X509Certificate x509cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));    		ret.add(x509cert);    		    	}    	log.debug("<getCertCollectionFromArray: "+ret.size());    	return ret;    }        /**     * Returns a certificate in PEM-format.     *     * @param cert the certificate to convert to PEM     * @return byte array containing PEM certificate     * @exception IOException if the stream cannot be read.     * @exception CertificateException if the stream does not contain a correct certificate.     */    public static byte[] getPEMFromCerts(Collection certs)    throws CertificateException {        String beginKey = "-----BEGIN CERTIFICATE-----";        String endKey = "-----END CERTIFICATE-----";        ByteArrayOutputStream ostr = new ByteArrayOutputStream();        PrintStream opstr = new PrintStream(ostr);        Iterator iter = certs.iterator();        while (iter.hasNext()) {            X509Certificate cert = (X509Certificate)iter.next();            byte[] certbuf = Base64.encode(cert.getEncoded());            opstr.println("Subject: "+cert.getSubjectDN());            opstr.println("Issuer: "+cert.getIssuerDN());            opstr.println(beginKey);            opstr.println(new String(certbuf));            opstr.println(endKey);        }        opstr.close();        byte[] ret = ostr.toByteArray();        return ret;    }    /**     * Creates X509Certificate from byte[].     *     * @param cert byte array containing certificate in DER-format     *     * @return X509Certificate     *     * @throws CertificateException if the byte array does not contain a proper certificate.     * @throws IOException if the byte array cannot be read.     */    public static X509Certificate getCertfromByteArray(byte[] cert)        throws CertificateException {        log.debug(">getCertfromByteArray:");        CertificateFactory cf = CertTools.getCertificateFactory();        X509Certificate x509cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert));        log.debug("<getCertfromByteArray:");        return x509cert;    } // getCertfromByteArray    /**     * Creates X509CRL from byte[].     *     * @param crl byte array containing CRL in DER-format     *     * @return X509CRL     *     * @throws IOException if the byte array can not be read.     * @throws CertificateException if the byte arrayen does not contani a correct CRL.     * @throws CRLException if the byte arrayen does not contani a correct CRL.     */    public static X509CRL getCRLfromByteArray(byte[] crl)        throws IOException, CRLException {        log.debug(">getCRLfromByteArray:");        if (crl == null) {            throw new IOException("Cannot read byte[] that is 'null'!");        }        CertificateFactory cf = CertTools.getCertificateFactory();        X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl));        log.debug("<getCRLfromByteArray:");        return x509crl;    } // getCRLfromByteArray    /**     * Checks if a certificate is self signed by verifying if subject and issuer are the same.     *     * @param cert the certificate that skall be checked.     *     * @return boolean true if the certificate has the same issuer and subject, false otherwise.     */    public static boolean isSelfSigned(X509Certificate cert) {        log.debug(">isSelfSigned: cert: " + CertTools.getIssuerDN(cert) + "\n" +            CertTools.getSubjectDN(cert));        boolean ret = CertTools.getSubjectDN(cert).equals(CertTools.getIssuerDN(cert));        log.debug("<isSelfSigned:" + ret);        return ret;    } // isSelfSigned    /**     * Generate a selfsigned certiicate.     *     * @param dn subject and issuer DN     * @param validity in days     * @param policyId policy string ('2.5.29.32.0') or null     * @param privKey private key     * @param pubKey public key     * @param sigAlg signature algorithm, you can use one of the contants CATokenInfo.SIGALG_XXX     * @param isCA boolean true or false     *     * @return X509Certificate, self signed     *     * @throws NoSuchAlgorithmException DOCUMENT ME!     * @throws SignatureException DOCUMENT ME!     * @throws InvalidKeyException DOCUMENT ME!     * @throws IllegalStateException      * @throws CertificateEncodingException      */    public static X509Certificate genSelfCert(String dn, long validity, String policyId,        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA)     	throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException {    	        int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;    	return genSelfCertForPurpose(dn, validity, policyId, privKey, pubKey, sigAlg, isCA, keyusage);    	    } //genselfCert    /**     * Generate a selfsigned certiicate with possibility to specify key usage.     *     * @param dn subject and issuer DN     * @param validity in days     * @param policyId policy string ('2.5.29.32.0') or null     * @param privKey private key     * @param pubKey public key     * @param sigAlg signature algorithm, you can use one of the contants CATokenInfo.SIGALG_XXX     * @param isCA boolean true or false     * @param keyusage as defined by constants in X509KeyUsage     *     * @return X509Certificate, self signed     *

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -