📄 x509cert.java
字号:
Date thisUpdate = new Date();
Date nextUpdate = new Date();
// crlperiod is hours = crlperiod*60*60*1000 milliseconds
nextUpdate.setTime(nextUpdate.getTime() + (crlperiod * 60 * 60 * 1000));
X509V2CRLGenerator crlgen = new X509V2CRLGenerator();
crlgen.setThisUpdate(thisUpdate);
crlgen.setNextUpdate(nextUpdate);
crlgen.setSignatureAlgorithm(signaturealgorithm);
// The CA issues & signs the CRL
crlgen.setIssuerDN(new X509Principal(cacert.getSubjectDN().toString()));
for (int i = 0; i < certserialnumbers.length; i++) {
crlgen.addCRLEntry(certserialnumbers[i], thisUpdate, 0);
}
crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier,
false,
CertTools.createAuthorityKeyId(cacert.getPublicKey()));
CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
crlgen.addExtension(X509Extensions.CRLNumber.getId(), false, crlnum);
crl = crlgen.generateX509CRL(caprivkey);
return crl;
} catch (Exception e) {
e.printStackTrace();
throw new CertificateException(e.getMessage());
}
}
/**
* Verify a certificate
*
* @param cert certificate to verify
* @param cacert CA's certificate
* @param crl CRL
* @return status (INVALID, REVOKED, EXPIRED or VERIFIED)
* @throws CertificateException
*/
public static String verifyCertificate(X509Certificate cert
, X509Certificate cacert
, X509CRL crl) throws CertificateException {
String status = "INVALID";
try {
if (crl.isRevoked(cert)) {
status = "REVOKED";
} else {
try {
cert.checkValidity(new Date());
} catch (Exception vae) {
status = "EXPIRED";
}
if (!status.equals("EXPIRED")) {
try {
cert.verify(cacert.getPublicKey());
status = "VERIFIED";
} catch (Exception vee) {
status = "INVALID";
}
}
}
return status;
} catch (Exception e) {
e.printStackTrace();
throw new CertificateException(e.getMessage());
}
}
/**
* Encodes a certificate as a PEM formatted string
*
* @param cert X.509 certificate
* @return certificate as PEM encoded string
* @throws CertificateEncodingException
*/
public static String getCertificateAsPem(X509Certificate cert) throws CertificateEncodingException {
byte output[] = cert.getEncoded();
byte certB64[] = Base64.encode(output);
return "-----BEGIN CERTIFICATE-----\n" + new String(certB64) + "\n-----END CERTIFICATE-----";
}
/**
* Encodes a private key as a PEM formatted string
*
* @param privatekey private key
* @return private key as PEM encoded string
*/
public static String getPrivateAsPem(PrivateKey privatekey) {
byte output[] = privatekey.getEncoded();
byte certB64[] = Base64.encode(output);
return "-----BEGIN PRIVATE KEY-----\n" + new String(certB64) + "\n-----END PRIVATE KEY-----";
}
/**
* Saves certificate and corresponding private key as a P12 keystore
*
* @param cert X.509 certificate
* @param signedby X.509 certificate of the signer
* @param privatekey private key
* @param keystore keystore filename and location
* @param entryname keystore entry name
* @param password keystore password
* @throws KeyStoreException P12 keystore error
* @throws NoSuchProviderException unknown JCE provider
* @throws Exception other errors
*/
public static void saveAsP12(X509Certificate cert
, X509Certificate signedby
, PrivateKey privatekey
, String keystore
, String entryname
, StringBuffer password) throws KeyStoreException, NoSuchProviderException, Exception {
// Store certificate in PKCS#12 store
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store = KeyTools.createP12(entryname, privatekey, cert, signedby);
store.store(new FileOutputStream(keystore), password.toString().toCharArray());
}
/**
* Read certificate from PKCS12 keystore
*
* @param keystore keystore filename and location
* @param entryname keystore entry name
* @param password keystore password
* @return X.509 certificate
* @throws KeyStoreException P12 keystore error
* @throws NoSuchAlgorithmException unknown algorithm
* @throws NoSuchProviderException unknown provider
* @throws IOException I/O errors
* @throws CertificateException
*/
public static X509Certificate getCertificateFromP12(String keystore
, String entryname
, StringBuffer password) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, IOException, CertificateException {
// read keystore
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(new FileInputStream(keystore), password.toString().toCharArray());
Certificate[] certchain = KeyTools.getCertChain(store, entryname);
return (X509Certificate) certchain[0];
}
/**
* Read CA certificate from PKCS12 keystore
*
* @param keystore keystore filename and location
* @param entryname keystore entry name
* @param password keystore password
* @return CA X.509 certificate
* @throws KeyStoreException P12 keystore error
* @throws NoSuchAlgorithmException unknown algorithm
* @throws NoSuchProviderException unknown provider
* @throws IOException I/O errors
* @throws CertificateException
*/
public static X509Certificate getCACertificateFromP12(String keystore
, String entryname
, StringBuffer password) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, IOException, CertificateException {
// read keystore
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(new FileInputStream(keystore), password.toString().toCharArray());
Certificate[] certchain = KeyTools.getCertChain(store, entryname);
return (X509Certificate) certchain[certchain.length - 1];
}
/**
* Read private key from PKCS12 keystore
*
* @param keystore keystore filename and location
* @param entryname keystore entry name
* @param password keystore password
* @return private key
* @throws KeyStoreException P12 keystore error
* @throws NoSuchAlgorithmException unknown algorithm
* @throws NoSuchProviderException unknown provider
* @throws IOException I/O errors
* @throws CertificateException
* @throws UnrecoverableKeyException
*/
public static PrivateKey getPrivateFromP12(String keystore
, String entryname
, StringBuffer password) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, IOException, CertificateException, UnrecoverableKeyException {
// read keystore
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
store.load(new FileInputStream(keystore), password.toString().toCharArray());
return (PrivateKey) store.getKey(entryname, password.toString().toCharArray());
}
/**
* Replaces all occurrences of a string in a text with another string
*
* @param text text
* @param repl string to replace
* @param with replacement string
* @return new string
*/
public static String replace(String text, String repl, String with) {
if (text == null) {
return null;
}
StringBuffer buf = new StringBuffer(text.length());
int start = 0, end = 0;
while ((end = text.indexOf(repl, start)) != -1) {
buf.append(text.substring(start, end)).append(with);
start = end + repl.length();
}
buf.append(text.substring(start));
return buf.toString();
}
/**
* Reads a PKCS10 certification request from a PEM string
*
* @param request the certification request as a PEM string
* @return certification request
* @throws CertificateException
*/
public static PKCS10CertificationRequest getPKCS10Request(String request) throws CertificateException {
byte[] buffer;
PKCS10CertificationRequest pkcs10 = null;
try {
try {
// A real PKCS10 PEM request
String beginKey = "-----BEGIN CERTIFICATE REQUEST-----";
String endKey = "-----END CERTIFICATE REQUEST-----";
buffer = FileTools.getBytesFromPEM(request.getBytes(), beginKey, endKey);
} catch (IOException e) {
try {
// Keytool PKCS10 PEM request
String beginKey = "-----BEGIN NEW CERTIFICATE REQUEST-----";
String endKey = "-----END NEW CERTIFICATE REQUEST-----";
buffer = FileTools.getBytesFromPEM(request.getBytes(), beginKey, endKey);
} catch (IOException ioe) {
// IE PKCS10 Base64 coded request
// FIX:IE generates cariage returns on Windows machines
// , so we strip them out (else we get an error)
request = replace(request, "\n", "");
request = replace(request, "\r", "");
buffer = Base64.decode(request.getBytes());
}
}
DERObject derobj = new DERInputStream(new ByteArrayInputStream(buffer)).readObject();
ASN1Sequence seq = (ASN1Sequence) derobj;
pkcs10 = new PKCS10CertificationRequest(seq);
if (pkcs10.verify() == false) {
throw new CertificateException("Not a valid PKCS10 request");
}
return pkcs10;
} catch (Exception e) {
e.printStackTrace();
throw new CertificateException(e.getMessage());
}
}
/**
* Reads a Netscape formatted certification request from a PEM string
*
* @param request the certification request as a PEM string
* @return certification request
* @throws CertificateException
*/
public static NetscapeCertRequest getNetscapeRequest(String request) throws CertificateException {
byte[] buffer;
NetscapeCertRequest nscr = null;
try {
// FIX: Netscape/Mozilla generates cariage returns on Windows machines
// , so we strip them out (else we get an error)
request = replace(request, "\n", "");
request = replace(request, "\r", "");
buffer = Base64.decode(request.getBytes());
DERInputStream in = new DERInputStream(new ByteArrayInputStream(buffer));
DERSequence spkac = (DERSequence) in.readObject();
nscr = new NetscapeCertRequest(spkac);
nscr.setChallenge("challenge");
if (nscr.verify("challenge") == false) {
throw new CertificateException("Not a valid Netscape request");
}
return nscr;
} catch (Exception e) {
e.printStackTrace();
throw new CertificateException(e.getMessage());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -