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 javaBy Keytool
1
2
3
4
5
6
7for(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
1 | keytool -exportcert -alias herong_key -keypass keypass -keystore herong.jks -storepass jkspass -file keytool_crt.der |
- Methods for getting certificate information
By keytoolBy openssl1
2keytool -list -v -keystore abc.p12 -storepass 1234 -storetype pkcs12
keytool -printcert -file keytool_crt.pem
1 | openssl x509 -in keytool_crt.pem -text -noout` |
- Convert p12 file from cert.p12 to cert2.p12 Merge it
1
2openssl pkcs12 -clcerts -nokeys -in cert.p12 -out usercert.pem // public key
openssl pkcs12 -nocerts -in cert.p12 -out userkey.pem // private keyopenssl 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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397package 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
1 | Authenticator auth = new Authenticator(); |
- With oracle java api, it can be used to get crl path elegantly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17CRLDistributionPointsExtension 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!