Learn certificate revocation list

jks -> p12 p12 -> pem (cer)
pem (cer) -> der

  • Convert a DER crl to PEM openssl crl -CAfile root.pem eCertCA1-10CRL2.pem

  • java keytool
    keytool -trustcacerts -import -alias alias -keystore cacerts.jks -file prod.der
    keytool -v -importkeystore -srckeystore cacerts3.jks -srcalias alias -destkeystore temp.p12 -deststoretype PKCS12 -srcstorepass password -deststorepass 1304478222600604
    keytool -list -v -keystore xxp12 -storepass 112233 -storetype pkcs12

  • export private key
    openssl pkcs12 -in prod.cer -out csr_private.key -nocerts -nodes -password pass:1304478222600604

  • print basic information in p12
    openssl pkcs12 -in xx.p12 -clcerts -nokeys|openssl x509 -text -noout

  • print information in PEM format certificate
    openssl x509 -in certificate.crt -text -noout

  • Export DER and PEM encoded certificate By java

<pre> for(String alias : keyStore.aliases()){ if (keyStore.isKeyEntry(alias)) { certificate = ((X509Certificate) keyStore.getCertificate(alias); } } byte[] cert_der_format = certificate.getEncoded(); // DER Encoded String cert_pem_format = X509Factory.BEGIN_CERT + new String(BASE64EnCoder.encode(cert_der_format)) + "\n" + X509Factory.END_CERT; // PEM Encoded </pre>

By Keytool
keytool -exportcert -alias herong_key -keypass keypass -keystore herong.jks -storepass jkspass -file keytool_crt.der
keytool -exportcert -alias herong_key -keypass keypass -keystore herong.jks -storepass jkspass -rfc -file keytool_crt.pem

  • Methods for getting certificate information
    By keytool
    keytool -list -v -keystore abc.p12 -storepass 1234 -storetype pkcs12 keytool -printcert -file keytool_crt.pem

By openssl
openssl x509 -in keytool_crt.pem -text -noout openssl x509 -in keytool_crt.der -inform der -text -noout

  • Convert p12 file from cert.p12 to cert2.p12 openssl pkcs12 -clcerts -nokeys -in cert.p12 -out usercert.pem // public key
    openssl pkcs12 -nocerts -in cert.p12 -out userkey.pem // private key
    Merge it
    openssl pkcs12 -export -out cert2.p12 -inkey ./userkey.pem -in ./usercert.pem

java ValidateCertUseCRL
DER vs. CRT vs. CER vs. PEM Certificates and How To Convert Them
DER (Distinguished Encoding Rules) certificate encoding
Verify Certificate is revoked by CRL
Using openssl to extract private key
SSL Converter
article-most-common-openssl-commands
normalize your certificate
Certificates: File Format & Conversion
keytool Exporting Certificates in DER and PEM
OpenSSL Validating Certificate Path
"keytool" Viewing Certificates in DER and PEM

  • No way to get CRL path using api from ibm jar, just find keyword CRLDistributionPoints by toString getExtension(new ObjectIdentifier(key)) as below;

    <!-- lang: java -->

    package xx;

import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PrivilegedActionException; import java.security.Signature; import java.security.UnrecoverableKeyException; import java.security.cert.CertPath; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.CertStore; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateParsingException; import java.security.cert.CollectionCertStoreParameters; import java.security.cert.PKIXCertPathValidatorResult; import java.security.cert.PKIXParameters; import java.security.cert.TrustAnchor; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.Vector;

import com.ibm.security.util.ObjectIdentifier; import com.ibm.security.x509.Extension; import com.ibm.security.x509.X509CertImpl;

public class Authenticator { private static final String start = "-----BEGIN CERTIFICATE-----\n"; private static final String end = "-----END CERTIFICATE-----";

private ResourceBundle m_configuration = ResourceBundle.getBundle("dh.properties.pkcs12");
private KeyStore m_keyStore = null;
private boolean keyStoreLoaded = false;
private String certificateID = "";
private X509Certificate certificate;
private String password = "";

public KeyStore loadKeyStore(final InputStream inStream, final String password) throws KeyStoreException,
		NoSuchAlgorithmException, CertificateException, IOException {
	String keyStoreType = m_configuration.getString("KEY_STORE_TYPE");
	try {
		m_keyStore = KeyStore.getInstance(keyStoreType);
	} catch (KeyStoreException e) {
		e.printStackTrace();
		throw e;
	}

	System.out.println("load the p12 file");
	if (password != null) {
		this.password = password;
		m_keyStore.load(inStream, password.toCharArray());
	} else {
		m_keyStore.load(inStream, null);
	}

	System.out.println("file is loaded successful");
	keyStoreLoaded = true;

	return m_keyStore;
}

public String getCertificateID() throws KeyStoreException {
	System.out.println("calling getCertificateID()"); //$IGN_Avoid_standard_output_input_error$<working as intended> //$IGN_Remove_System_print_or_println_statements$<working as intended>
	if (!keyStoreLoaded) {
		throw new KeyStoreException("Key store has not been loaded.");
	}

	StringBuffer result = new StringBuffer();

	try {
		Enumeration<String> aliases = m_keyStore.aliases();
		while (aliases.hasMoreElements()) {
			String alias = aliases.nextElement();
			if (m_keyStore.isKeyEntry(alias)) {
				result.append(alias);
			}
		}
	} catch (KeyStoreException e) {
		e.printStackTrace();
		throw e;
	}

	return result.toString();
}

public String getEncocdedCertificate() throws KeyStoreException {
	System.out.println("calling getCertificate()"); //$IGN_Avoid_standard_output_input_error$<working as intended> //$IGN_Remove_System_print_or_println_statements$<working as intended>

	if (!keyStoreLoaded) {
		throw new KeyStoreException("Key store has not been loaded.");
	}

	try {
		certificate = retrieveCertificate();
	} catch (Exception e) {
		e.printStackTrace();
		return "";
	}

	try {
		return start + new String(BASE64Coder.encode(certificate.getEncoded())) + "\n" + end;
	} catch (CertificateEncodingException e) {
		e.printStackTrace();
	}
	return "";
}

private X509Certificate retrieveCertificate() throws KeyStoreException, CertificateExpiredException,
		CertificateNotYetValidException {
	if (!keyStoreLoaded) {
		throw new KeyStoreException("Key store has not been loaded.");
	}

	Certificate cert = m_keyStore.getCertificate(certificateID);

	if (cert == null) {
		//System.out.println("Searching for all aliases");
		Enumeration<String> aliases = m_keyStore.aliases();

		while (aliases.hasMoreElements()) {
			String alias = aliases.nextElement().trim();

			if (m_keyStore.isKeyEntry(alias)) {
				cert = m_keyStore.getCertificate(alias);

				if (cert == null) {
					continue;
				}

			}
		}
	}

	if (cert instanceof X509Certificate) {
		certificate = (X509Certificate) cert;
	}

	try { //$IGN_Place_try_catch_out_of_loop$<working as intended>
		certificate.checkValidity();
	} catch (CertificateExpiredException e) {
		System.out.println(e);
		throw e;
	} catch (CertificateNotYetValidException e) {
		System.out.println(e);
		throw e;
	} //$IGN_Always_use_caught_exception$<working as intended>

	return certificate;
}

public String getSubjectDN() throws CertificateExpiredException, CertificateNotYetValidException, KeyStoreException {
	certificate = retrieveCertificate();
	try {
		String principal = certificate.getSubjectX500Principal().getName();
		return principal;
	} catch (Exception e) {
		String subjectDNName = certificate.getSubjectDN().getName();
		return subjectDNName;
	}
}

public void checkCRL() throws CertPathValidatorException {
	System.out.println("calling checkCRL");
	if (certificate == null) {
		try {
			certificate = retrieveCertificate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	CertPath cp = null;
	Vector<Certificate> certs = new Vector<Certificate>();

	// load the cert to be checked
	certs.add(certificate);

	// handle location of CRL
	//System.out.println("Using the CRL specified in the " + "cert to check the revocation status of: "
	//	+ certs.elementAt(0));
	System.setProperty("com.sun.security.enableCRLDP", "true");

	CertificateFactory cf = null;
	// init cert path
	PKIXParameters params = null;
	try {
		cf = CertificateFactory.getInstance("X509");
		cp = (CertPath) cf.generateCertPath(certs);

		// load the root CA cert 
		String rootCaCert = m_configuration.getString("ROOT_CA_CERT");
		X509Certificate rootCACert = getCertFromFile(rootCaCert);
		System.out.println("rootCACert = " + rootCACert);

		// init trusted certs
		TrustAnchor ta = new TrustAnchor(rootCACert, null);
		Set<TrustAnchor> trustedCerts = new HashSet<TrustAnchor>();
		trustedCerts.add(ta);

		// init PKIX parameters
		params = new PKIXParameters(trustedCerts);
	} catch (CertificateException e) {
		System.out.println(e);
		return;
	} catch (Exception e) {
		System.out.println(e);
		return;
	}

	URL url = null;
	X509CertImpl certificateImpl = (X509CertImpl) certificate;

	Set<String> oids = certificateImpl.getNonCriticalExtensionOIDs();
	for (String key : oids) {
		System.out.println("key = " + key);
		try {
			Extension e = certificateImpl.getExtension(new ObjectIdentifier(key));
			String val = e.toString();
			if (val.indexOf("CRLDistributionPoints") != -1) {
				int start = val.indexOf("http");
				int end = val.indexOf(".crl");
				url = new URL(val.substring(start, end + 4));
			}
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}

	// load the CRL
	try {
		if (url != null) {
			URLConnection connection = url.openConnection();
			connection.setDoInput(true);
			connection.setUseCaches(false);
			DataInputStream inStream = new DataInputStream(connection.getInputStream());
			X509CRL crl = (X509CRL) cf.generateCRL(inStream);
			inStream.close();

			params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(Collections
					.singletonList(crl))));
			params.setRevocationEnabled(true);
		}
	} catch (Exception e) {
		System.out.println("fail to load url " + url);
		System.out.println(e);
	}

	// perform validation
	try {
		CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

		PKIXCertPathValidatorResult cpv_result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
		X509Certificate trustedCert = (X509Certificate) cpv_result.getTrustAnchor().getTrustedCert();
		if (trustedCert == null) {
			System.out.println("Trusted Cert = NULL");
		} else {
			System.out.println("Trusted CA DN = " + trustedCert.getSubjectDN());
		}
		System.out.println("CERTIFICATE VALIDATION SUCCEEDED");
	} catch (NoSuchAlgorithmException e) {
		System.out.println(e);
	} catch (CertPathValidatorException e) {
		e.printStackTrace();
		throw e;
	} catch (InvalidAlgorithmParameterException e) {
		System.out.println(e);
	}
}

private static X509Certificate getCertFromFile(String path) {
	X509Certificate cert = null;
	try {
		File certFile = new File(path);
		if (!certFile.canRead())
			throw new IOException(" File " + certFile.toString() + " is unreadable");

		FileInputStream fis = new FileInputStream(path);
		CertificateFactory cf = CertificateFactory.getInstance("X509");
		cert = (X509Certificate) cf.generateCertificate(fis);

	} catch (Exception e) {
		System.out.println("Can't construct X509 Certificate. " + e.getMessage());
	}
	return cert;
}

/**
 * GeneralName ::= CHOICE {
 *     otherName                       [0]     OtherName,
 *     rfc822Name                      [1]     IA5String,
 *     dNSName                         [2]     IA5String,
 *     x400Address                     [3]     ORAddress,
 *     directoryName                   [4]     Name,
 *     ediPartyName                    [5]     EDIPartyName,
 *     uniformResourceIdentifier       [6]     IA5String,
 *     iPAddress                       [7]     OCTET STRING,
 *     registeredID                    [8]     OBJECT IDENTIFIER}
 * @see java.security.cert.X509Certificate#getSubjectAlternativeNames()
 * @link http://www.ietf.org/rfc/rfc2459.txt
 */
private String getDomainName() {
	String domainName = "";

	try {
		Iterator it = certificate.getSubjectAlternativeNames().iterator();
		while (it.hasNext()) {
			List list = (List) it.next();
			if (((Integer) list.get(0)).intValue() == 2) {
				domainName = list.get(1).toString();
			}
		}

	} catch (CertificateParsingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return domainName;
}

private String encodeID(String hkid) {
	Signature signature = null;
	PrivateKey key = null;
	String hashAlgorithm = "SHA-1";
	try {
		key = (PrivateKey) m_keyStore.getKey(getCertificateID(), this.password.toCharArray());
		String signingAlgorithm = "SHA1with" + key.getAlgorithm();
		signature = Signature.getInstance(signingAlgorithm);
	} catch (UnrecoverableKeyException e) {
		System.out.println("UnrecoverableKeyException " + e);
	} catch (KeyStoreException e) {
		System.out.println("KeyStoreException " + e);
	} catch (NoSuchAlgorithmException e) {
		System.out.println("NoSuchAlgorithmException " + e);
	}

	try {
		signature.initSign(key);
		signature.update(hkid.getBytes("UTF-8"));

		byte[] signed = signature.sign();
		MessageDigest digest = null;
		digest = MessageDigest.getInstance(hashAlgorithm);
		//System.out.println("Got MD algorithm");
		String encodedID = new String(BASE64Coder.encode(digest.digest(signed)));
		System.out.println("Done hashing");
		return encodedID;
		//signature.initVerify(certificate.getPublicKey());
		/*if (signature.verify(signed)) {
			
		}*/
	} catch (Exception ignore) {
		System.out.println("Exception " + ignore);
	}
	return "";
}

public boolean checkHKID(String hkid) {
	System.out.println("check HKID");
	String domainName = getDomainName();
	String encodedID = encodeID(hkid);

	System.out.println("domainName = " + domainName);
	System.out.println("encodedID = " + encodedID);

	if (encodedID.length() != domainName.length())
		return false;

	for (int i = 0; i < encodedID.length(); i++)
		if (encodedID.charAt(i) != domainName.charAt(i))
			return false;

	return true;
}

}

------- Class 2 --------- Using it Authenticator auth = new Authenticator(); try { auth.loadKeyStore(in, certPin); } catch (KeyStoreException e) { System.out.println("KeyStoreException error = " + e.getMessage()); errMsg = bundle.getString(ErrMsgConfig.ECERT00007); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException error = " + e.getMessage()); errMsg = bundle.getString(ErrMsgConfig.ECERT00019); } catch (CertificateException e) { System.out.println("CertificateException error = " + e.getMessage()); errMsg = bundle.getString(ErrMsgConfig.ECERT00007); } catch (IOException e) { System.out.println("IOException error = " + e.getMessage()); errMsg = bundle.getString(ErrMsgConfig.ECERT00019); }

		String subjectDN = "";

		if (errMsg.length() == 0) {
			try {
				subjectDN = auth.getSubjectDN();
			} catch (CertificateExpiredException e) {
				System.out.println("CertificateExpiredException error = " + e.getMessage());
				errMsg = bundle.getString(ErrMsgConfig.ECERT00002);
			} catch (CertificateNotYetValidException e) {
				System.out.println("CertificateNotYetValidException error = " + e.getMessage());
				errMsg = bundle.getString(ErrMsgConfig.ECERT00003);
			}
		}

		System.out.println("subject: " + subjectDN);
		if (errMsg.length() == 0) {
			try {
				boolean valid = RmiSignVerifier.checkCRL(auth.getEncocdedCertificate());
				if (!valid) {
					errMsg = bundle.getString(ErrMsgConfig.ECERT00014);
				}
			} catch (CertPathValidatorException e) {
				System.out.println("CertPathValidatorException error = " + e.getMessage());
				errMsg = bundle.getString(ErrMsgConfig.ECERT00004);
			}
		}

		if (errMsg.length() == 0) {
			req.setAttribute("errMsg", errMsg);

			List<Rdn> names = new LdapName(subjectDN).getRdns();
			for (Rdn name : names) {
				System.out.println("rdn " + name.getType() + ", " + name.getValue());
				String value = name.getValue().toString();

				if (name.getType().equals("O")) {
					if (value.indexOf("Hongkong Post") == -1) {
						errMsg = bundle.getString(ErrMsgConfig.ECERT00007);
					}

					if (value.indexOf(CERT_TYPE_ORGANIZATIONAL) != -1) {
						certType = CERT_TYPE_ORGANIZATIONAL;
					} else {
						certType = CERT_TYPE_PERSONAL;
					}
				}

				if (name.getType().equals("OU")) {
					Pattern p = Pattern.compile("\\d+");

					if (p.matcher(value).matches()) { // check digit
						if (value.length() > 10) {
							brc = value.substring(0, 8);
							brcBranchCode = value.substring(8, 11);
						} else {
							srn = value;
							session.setAttribute("CERT_SRC_NO", srn);
							System.out.println("srn " + srn);
						}
					}
				}
				if (name.getType().equals("CN")) {
					holdername = value;
					session.setAttribute("holdername", holdername);
					System.out.println("holdername: " + holdername);
				}
			}

			System.out.println("certificate Type " + certType);

			if (certType.equals(CERT_TYPE_PERSONAL)) {
				if (!auth.checkHKID(userHKID)) {
					errMsg = bundle.getString(ErrMsgConfig.ECERT00008);
				}
			}
		}
  • With oracle java api, it can be used to get crl path elegantly.

    <!-- lang: java -->

    CRLDistributionPointsExtension crlDistributionPointsExtension = certificateImpl .getCRLDistributionPointsExtension(); if (crlDistributionPointsExtension != null) { try { for (DistributionPoint distributionPoint : ((List<DistributionPoint>) crlDistributionPointsExtension .get(CRLDistributionPointsExtension.POINTS))) { for (GeneralName generalName : distributionPoint.getFullName().names()) { String generalNameString = generalName.toString(); System.out.println(generalNameString); String crlURLString = generalNameString.substring(9); crlUrl = new URL(crlURLString); } } } catch (Exception ex) { throw new CertPathValidatorException(ex); } }

  • But finally check whether CRL is revoked, just call crl.isrevoked to work. Damn!

转载于:https://my.oschina.net/l1z2g9/blog/357670

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值