List of usage examples for java.security KeyStore load
public final void load(LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;// w w w.j a va2 s .co m String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:io.kubernetes.client.util.SSLUtils.java
private static void loadDefaultKeyStoreFile(KeyStore keyStore, char[] keyStorePassphrase) throws CertificateException, NoSuchAlgorithmException, IOException { String keyStorePath = System.getProperty("javax.net.ssl.keyStore"); if (keyStorePath != null && keyStorePath.length() > 0) { File keyStoreFile = new File(keyStorePath); if (loadDefaultStoreFile(keyStore, keyStoreFile, keyStorePassphrase)) { return; }/* www. jav a 2 s . co m*/ } keyStore.load(null); }
From source file:org.wso2.emm.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *//*w ww.jav a 2 s . c o m*/ public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException e) { Log.e(TAG, e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:org.wso2.iot.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *//*from w ww.j a v a 2 s.c o m*/ public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) { Log.e(TAG, e.getMessage(), e); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:com.netscape.cmstools.pkcs11.PKCS11CertRemoveCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();//from www . ja va2 s . c o m return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String[] cmdArgs = cmd.getArgs(); if (cmdArgs.length < 1) { throw new Exception("Missing cert ID."); } String alias = cmdArgs[0]; String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Certificate cert = ks.getCertificate(alias); if (cert == null) { throw new Exception("Certificate not found: " + alias); } ks.deleteEntry(alias); }
From source file:com.netscape.cmstools.pkcs11.PKCS11CertShowCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();/*w w w. j av a 2 s .c om*/ return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String[] cmdArgs = cmd.getArgs(); if (cmdArgs.length < 1) { throw new Exception("Missing cert ID."); } String alias = cmdArgs[0]; String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Certificate cert = ks.getCertificate(alias); if (cert == null) { throw new Exception("Certificate not found: " + alias); } PKCS11CertCLI.printCertInfo(alias, cert); }
From source file:com.netscape.cmstools.pkcs11.PKCS11KeyRemoveCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();/*from ww w.j a v a2 s . co m*/ return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String[] cmdArgs = cmd.getArgs(); if (cmdArgs.length < 1) { throw new Exception("Missing key ID."); } String alias = cmdArgs[0]; String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Key key = ks.getKey(alias, null); if (key == null) { throw new Exception("Key not found: " + alias); } ks.deleteEntry(alias); }
From source file:com.netscape.cmstools.pkcs11.PKCS11KeyShowCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();//from www. j ava2 s . co m return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String[] cmdArgs = cmd.getArgs(); if (cmdArgs.length < 1) { throw new Exception("Missing key ID."); } String alias = cmdArgs[0]; String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Key key = ks.getKey(alias, null); if (key == null) { throw new Exception("Key not found: " + alias); } PKCS11KeyCLI.printKeyInfo(alias, key); }
From source file:com.netscape.cmstools.pkcs11.PKCS11CertFindCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();//w ww . j av a 2 s. c om return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Enumeration<String> aliases = ks.aliases(); boolean first = true; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert == null) { continue; } if (first) { first = false; } else { System.out.println(); } PKCS11CertCLI.printCertInfo(alias, cert); } }
From source file:com.github.mrstampy.gameboot.otp.OtpTestConfiguration.java
/** * Client context./*from ww w . ja v a2 s. com*/ * * @return the SSL context * @throws Exception * the exception */ @Bean(name = CLIENT_SSL_CONTEXT) public SSLContext clientContext() throws Exception { CertificateFactory cf = CertificateFactory.getInstance(X_509); Certificate cert = cf.generateCertificate(getResource(CERT_LOCATION)); KeyStore keystore = getKeyStore(); keystore.load(null); keystore.setCertificateEntry(ALIAS, cert); return createContext(keystore, null); }