📄 keystoremanager.java
字号:
v.add("-keystore");
v.add(keyStoreFile.getAbsolutePath());
v.add("-dname");
v.add(dname);
v.add("-storetype");
v.add(keyStoreType.getName());
v.add("-storepass");
v.add(keyStorePassword);
v.add("-keypass");
v.add(keyStorePassword);
runner = new CommandRunner(v);
runner.runCommand();
updateRepository(false);
} catch (Exception e) {
log.error("Failed to create key.", e);
throw new Exception(runner == null ? e.getMessage() : parseKeytoolOutput(runner.getOutput()));
}
}
/**
* Import a certificate from a file and store with the specified a alias.
* File must be X509 and Base 64 or DER encoded.
*
* @param alias alias to store cert. under
* @param certFile file contain certificate
* @param keyPass key password or <code>null</code> for default
* @throws Exception on any error
*/
public void importCert(String alias, File certFile, String keyPass) throws Exception {
checkKeyStore();
if (!isKeyStoreExists()) {
createKeyStore();
}
/*
* Because an empty keystore file is not valid, delete the key first
* then let genkey create a new keystore
*/
if (isKeyStoreEmpty()) {
if (!getKeyStoreFile().delete()) {
throw new Exception("Could not delete key store.");
}
}
CommandRunner runner = null;
try {
if (log.isInfoEnabled())
log.info("Importing certificate for " + alias + " from " + certFile.getAbsolutePath());
String keyPassword = getKeyStorePassword();
Vector v = new Vector();
v.add(KEY_TOOL);
v.add("-import");
v.add("-trustcacerts");
v.add("-noprompt");
v.add("-file");
v.add(certFile.getAbsolutePath());
v.add("-alias");
v.add(alias);
v.add("-keystore");
v.add(keyStoreFile.getAbsolutePath());
v.add("-storepass");
v.add(keyPassword);
v.add("-keypass");
v.add(keyPass == null ? DEFAULT_KEY_PASSWORD : keyPass);
v.add("-storetype");
v.add(keyStoreType.getName().toLowerCase());
runner = new CommandRunner(v);
runner.runCommand();
updateRepository(false);
} catch (Exception e) {
log.error("Failed to import certficate.", e);
throw new Exception(runner == null ? e.getMessage() : parseKeytoolOutput(runner.getOutput()));
}
if (log.isInfoEnabled())
log.info("Certificate for " + alias + " imported from " + certFile.getAbsolutePath());
}
/**
* Generate a certificate sigining request for the key with the specfied
* alias.
*
* @param alias alias to generate CSR for
* @return CSR as a string
* @throws Exception on any error
*/
public String generateCSR(String alias, String keyPass) throws Exception {
checkKeyStore();
if (!isKeyStoreExists()) {
throw new Exception("Key store doesn't exists. CSR cannot be generated.");
}
CommandRunner runner = null;
InputStream in = null;
try {
String keyPassword = getKeyStorePassword();
Vector v = new Vector();
v.add(KEY_TOOL);
v.add("-certreq");
v.add("-alias");
v.add(alias);
v.add("-keyalg");
v.add("RSA");
v.add("-keystore");
v.add(keyStoreFile.getAbsolutePath());
v.add("-storepass");
v.add(keyPassword);
v.add("-file");
File csrFile = new File(ContextHolder.getContext().getConfDirectory(), "sslexplorer.csr");
v.add(csrFile.getAbsolutePath());
v.add("-keypass");
v.add(keyPass == null ? DEFAULT_KEY_PASSWORD : keyPass);
runner = new CommandRunner(v);
runner.runCommand();
in = new FileInputStream(csrFile);
return Util.loadStreamToString(in, null);
} catch (Exception e) {
log.error("Failed to create key.", e);
throw new Exception(runner == null ? e.getMessage() : parseKeytoolOutput(runner.getOutput()));
} finally {
Util.closeStream(in);
}
}
/**
* Create a new key store.
* <p>
* We dont actually create a keystore, we just create a zero length file as
* there doesnt seem to be a way of creating an empty keystore using
* keytool.
*
* @throws IOException on any error
*/
public void createKeyStore() throws IOException {
if (isKeyStoreExists()) {
throw new IOException("Key store already exists.");
}
FileOutputStream out = null;
try {
out = new FileOutputStream(getKeyStoreFile());
} finally {
Util.closeStream(out);
}
}
/**
* Delete the key store.
*
* @throws IOException
*/
public void deleteKeyStore() throws IOException {
if (!isKeyStoreExists()) {
throw new IOException("Key store does not exist.");
}
if (!getKeyStoreFile().delete()) {
throw new IOException("Failed to delete " + getKeyStoreFile().getAbsolutePath() + ".");
}
updateRepository(true);
}
/**
* Delete a certificate from the key store given its alias.
*
* @param alias alias to remove
* @throws Exception on any error
*/
public void deleteCertificate(String alias) throws Exception {
checkKeyStore();
if (!isKeyStoreExists()) {
throw new Exception("Key store doesn't exists. Certificate cannot be deleted.");
}
CommandRunner runner = null;
try {
if (log.isInfoEnabled())
log.info("Deleting certificate for " + alias);
String keyPassword = getKeyStorePassword();
Vector v = new Vector();
v.add(KEY_TOOL);
v.add("-delete");
v.add("-alias");
v.add(alias);
v.add("-keystore");
v.add(keyStoreFile.getAbsolutePath());
v.add("-storepass");
v.add(keyPassword);
runner = new CommandRunner(v);
runner.runCommand();
updateRepository(false);
} catch (Exception e) {
log.error("Failed to delete certificate.", e);
throw new Exception(runner == null ? e.getMessage() : parseKeytoolOutput(runner.getOutput()));
}
if (log.isInfoEnabled())
log.info("Deleted certificate for " + alias);
}
/**
* Get a {@link KeyStoreType} given its name.
*
* @param name key store type name
* @return key store type
*/
public static KeyStoreType getKeyStoreType(String name) {
for (Iterator i = keyStoreTypes.iterator(); i.hasNext();) {
KeyStoreType t = (KeyStoreType) i.next();
if (t.getName().equals(name)) {
return t;
}
}
return null;
}
/**
* Get a list of supported {@link KeyStoreType} objects.
*
* @return list of support key store types
*/
public List getSupportedKeyStoreTypes() {
return keyStoreTypes;
}
/**
* Set the key store type for this key store manager.
*
* @param keyStoreType key store type
*/
public void setKeyStoreType(KeyStoreType keyStoreType) {
this.keyStoreType = keyStoreType;
initKeyStoreFile();
}
/**
* Get the key store type for this key store manager.
*
* @return key store type
*/
public KeyStoreType getKeyStoreType() {
return keyStoreType;
}
// Supporting methods
void initKeyStoreFile() {
this.keyStoreFile = new File(ContextHolder.getContext().getConfDirectory(), keyStoreName + ".keystore." + keyStoreType.getExtension());
}
void synchronizeWithRepository() throws IOException {
RepositoryStore store = RepositoryFactory.getRepository().getStore(KEYSTORE_REPOSITORY);
if (!store.hasEntry(keyStoreFile.getName())) {
keyStoreFile.createNewFile();
} else {
InputStream in = null;
OutputStream out = null;
try {
in = store.getEntryInputStream(keyStoreFile.getName());
out = new FileOutputStream(keyStoreFile);
Util.copy(in, out);
} finally {
Util.closeStream(in);
Util.closeStream(out);
}
}
}
void updateRepository(boolean remove) throws IOException {
RepositoryStore store = RepositoryFactory.getRepository().getStore(KEYSTORE_REPOSITORY);
if (remove) {
store.removeEntry(keyStoreFile.getName());
} else {
OutputStream out = null;
InputStream in = null;
try {
out = store.getEntryOutputStream(keyStoreFile.getName());
in = new FileInputStream(keyStoreFile);
Util.copy(in, out);
} finally {
Util.closeStream(in);
Util.closeStream(out);
}
}
}
/**
* Get the key store passwords
*
* @return keystore password
* @throws Exception
*/
public String getKeyStorePassword() throws Exception {
return storePassword;
}
boolean doIsCertificateTrused(String alias, KeyStore keyStore) throws Exception {
Certificate[] certs = keyStore.getCertificateChain(alias);
if (certs == null) {
if (log.isInfoEnabled())
log.info("No certs for " + alias + ", untrusted.");
} else if (certs.length > 1) {
X509Certificate x509cert = (X509Certificate) certs[certs.length - 1];
TrustedCACertStore store = new TrustedCACertStore();
ByteArrayInputStream bin = new ByteArrayInputStream(x509cert.getEncoded());
DERInputStream der = null;
try {
der = new DERInputStream(bin);
ASN1Sequence certificate = (ASN1Sequence) der.readObject();
com.maverick.crypto.asn1.x509.X509Certificate x509 = new com.maverick.crypto.asn1.x509.X509Certificate(
X509CertificateStructure.getInstance(certificate));
return store.isTrustedCertificate(x509, false, false);
} finally {
Util.closeStream(der);
}
}
return false;
}
String parseKeytoolOutput(String output) {
if (output.startsWith("keytool error: ")) {
int idx = output.indexOf(':', 14);
if (idx != -1) {
output = output.substring(idx + 1);
}
}
return output;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -