Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import sun.security.tools.keytool.CertAndKeyGen;
- import sun.security.x509.X500Name;
- import java.io.IOException;
- import java.security.InvalidKeyException;
- import java.security.KeyStore;
- import java.security.KeyStoreException;
- import java.security.NoSuchAlgorithmException;
- import java.security.NoSuchProviderException;
- import java.security.SignatureException;
- import java.security.cert.Certificate;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- public class CertificateUtils {
- public static final String KEY_TYPE_RSA = "RSA";
- public static final String SIG_ALG_SHA_RSA = "SHA1WithRSA";
- public static final int KEY_SIZE = 1024;
- public static final long CERT_VALIDITY = 365 * 24 * 3600L;
- public static final String ALIAS_PRIVATE = "private";
- public static final String ALIAS_CERT = "cert";
- public static final String IN_MEMORY_PWD = "notReallyImportant"; // this would only ever be relevant if/when persisted.
- private static final Logger LOGGER = LoggerFactory.getLogger(CertificateUtils.class);
- /**
- * @param certValues e.g. CN=Dave, OU=JavaSoft, O=Sun Microsystems, C=US
- * @return
- */
- public static KeyStore createSelfSigned(String certValues) {
- try {
- CertAndKeyGen keyGen = new CertAndKeyGen(KEY_TYPE_RSA, SIG_ALG_SHA_RSA);
- keyGen.generate(KEY_SIZE);
- KeyStore ks = emptyStore();
- if (ks == null) {
- return null;
- }
- X509Certificate certificate = keyGen.getSelfCertificate(new X500Name(certValues), CERT_VALIDITY);
- ks.setCertificateEntry(ALIAS_CERT, certificate);
- ks.setKeyEntry(ALIAS_PRIVATE, keyGen.getPrivateKey(), IN_MEMORY_PWD.toCharArray(), new Certificate[]{certificate});
- return ks;
- } catch (KeyStoreException | NoSuchAlgorithmException | NoSuchProviderException | CertificateException | SignatureException | InvalidKeyException | IOException e) {
- LOGGER.error("Cannot create self signed certificate.", e);
- }
- return null;
- }
- public static KeyStore createSelfSignedForHost(String host) {
- return createSelfSigned("CN=" + host);
- }
- public static KeyStore emptyStore() {
- try {
- KeyStore ks = KeyStore.getInstance("JKS");
- // Loading creates the store, can't do anything with it until it's loaded
- ks.load(null, IN_MEMORY_PWD.toCharArray());
- return ks;
- } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
- LOGGER.error("Cannot create empty keystore.", e);
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement