List of usage examples for java.security KeyStore store
public final void store(OutputStream stream, char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerSASLSSLTest.java
@org.junit.BeforeClass public static void setup() throws Exception { // JAAS Config file String basedir = System.getProperty("basedir"); if (basedir == null) { basedir = new File(".").getCanonicalPath(); }//w w w. j a v a2s . c o m File f = new File(basedir + "/src/test/resources/kafka_plain.jaas"); System.setProperty("java.security.auth.login.config", f.getPath()); // Create keys String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE"; String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE"; // Create a truststore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, "security".toCharArray()); serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30), "sspass", "myservicekey", "skpass", keystore); clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass", "myclientkey", "ckpass", keystore); File truststoreFile = File.createTempFile("kafkatruststore", ".jks"); try (OutputStream output = new FileOutputStream(truststoreFile)) { keystore.store(output, "security".toCharArray()); } truststorePath = truststoreFile.getPath(); zkServer = new TestingServer(); // Get a random port ServerSocket serverSocket = new ServerSocket(0); port = serverSocket.getLocalPort(); serverSocket.close(); final Properties props = new Properties(); props.put("broker.id", 1); props.put("host.name", "localhost"); props.put("port", port); props.put("log.dir", "/tmp/kafka"); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", Boolean.TRUE.toString()); // Enable SASL_SSL props.put("listeners", "SASL_SSL://localhost:" + port); props.put("security.inter.broker.protocol", "SASL_SSL"); props.put("sasl.enabled.mechanisms", "PLAIN"); props.put("sasl.mechanism.inter.broker.protocol", "PLAIN"); props.put("ssl.keystore.location", serviceKeystorePath); props.put("ssl.keystore.password", "sspass"); props.put("ssl.key.password", "skpass"); props.put("ssl.truststore.location", truststorePath); props.put("ssl.truststore.password", "security"); // Plug in Apache Ranger authorizer props.put("authorizer.class.name", "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer"); // Create users for testing UserGroupInformation.createUserForTesting("alice", new String[] { "IT" }); KafkaConfig config = new KafkaConfig(props); kafkaServer = new KafkaServerStartable(config); kafkaServer.startup(); // Create some topics ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$); final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false); AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$); AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$); }
From source file:org.panbox.core.pairing.file.PanboxFilePairingUtils.java
/** * Stores a pairing file at the specified path for the specified device and * type/*from ww w . j av a 2 s . c o m*/ * * @param outputFile * Pairing file to be saved * @param devicename * Name of the device that should be paired * @param password * Password of the identity */ public static PanboxFilePairingWriteReturnContainer storePairingFile(File outputFile, String devicename, char[] password, PairingType type, DeviceType devType, String eMail, String firstName, String lastName, PrivateKey privEncKey, X509Certificate encCert, PrivateKey privSignKey, X509Certificate signCert, Map<String, X509Certificate> devices, Collection<VCard> contacts) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container to: " + outputFile.getAbsolutePath()); ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(outputFile)); // 1. add device name to pairing file ZipArchiveEntry entry = new ZipArchiveEntry("devicename"); entry.setSize(devicename.getBytes().length); out.putArchiveEntry(entry); out.write(devicename.getBytes()); out.flush(); out.closeArchiveEntry(); // 2. add device name to pairing file entry = new ZipArchiveEntry("email"); entry.setSize(eMail.getBytes().length); out.putArchiveEntry(entry); out.write(eMail.getBytes()); out.flush(); out.closeArchiveEntry(); // 3. add device name to pairing file entry = new ZipArchiveEntry("firstname"); entry.setSize(firstName.getBytes().length); out.putArchiveEntry(entry); out.write(firstName.getBytes()); out.flush(); out.closeArchiveEntry(); // 4. add device name to pairing file entry = new ZipArchiveEntry("lastname"); entry.setSize(lastName.getBytes().length); out.putArchiveEntry(entry); out.write(lastName.getBytes()); out.flush(); out.closeArchiveEntry(); // 5. generate and add a new device key + cert for the newly device KeyPair devKey = CryptCore.generateKeypair(); X509Certificate devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(), new PairingIPersonDummy(eMail, firstName, lastName)); KeyStore devKeyStore = KeyStore.getInstance("PKCS12"); devKeyStore.load(null, null); devKeyStore.setKeyEntry(devicename, (Key) devKey.getPrivate(), password, new Certificate[] { devCert }); ByteArrayOutputStream baos = new ByteArrayOutputStream(); devKeyStore.store(baos, password); baos.flush(); byte[] data = baos.toByteArray(); entry = new ZipArchiveEntry("devicekey.p12"); entry.setSize(data.length); out.putArchiveEntry(entry); out.write(data); out.flush(); out.closeArchiveEntry(); // 6. add device certs and names for all known devices baos = new ByteArrayOutputStream(); ByteArrayOutputStream deviceNamesFile = new ByteArrayOutputStream(); KeyStore deviceKeyStore = KeyStore.getInstance("BKS"); deviceKeyStore.load(null, null); int i = 0; for (Entry<String, X509Certificate> device : devices.entrySet()) { deviceKeyStore.setCertificateEntry("device" + i, device.getValue()); deviceNamesFile.write(("device" + i + DELIMITER + device.getKey() + "\n").getBytes()); ++i; } deviceKeyStore.store(baos, password); baos.flush(); deviceNamesFile.flush(); byte[] data2 = deviceNamesFile.toByteArray(); entry = new ZipArchiveEntry("knownDevices.list"); entry.setSize(data2.length); out.putArchiveEntry(entry); out.write(data2); out.flush(); data = baos.toByteArray(); entry = new ZipArchiveEntry("knownDevices.bks"); entry.setSize(data.length); out.putArchiveEntry(entry); out.write(data); out.flush(); // 7. add vcard for all known contacts File tempContacts = File.createTempFile("panboxContacts", null); AbstractAddressbookManager.exportContacts(contacts, tempContacts); FileInputStream fis = new FileInputStream(tempContacts); data = new byte[(int) tempContacts.length()]; fis.read(data); fis.close(); tempContacts.delete(); entry = new ZipArchiveEntry("contacts.vcard"); entry.setSize(data.length); out.putArchiveEntry(entry); out.write(data); out.flush(); // 8. add owner certs or keys in case of main/restricted KeyStore ownerKeyStore = null; if (type == PairingType.MASTER) { ownerKeyStore = KeyStore.getInstance("PKCS12"); ownerKeyStore.load(null, null); ownerKeyStore.setKeyEntry("ownerEncKey", privEncKey, password, new Certificate[] { encCert }); ownerKeyStore.setKeyEntry("ownerSignKey", privSignKey, password, new Certificate[] { signCert }); entry = new ZipArchiveEntry("ownerKeys.p12"); } else { ownerKeyStore = KeyStore.getInstance("BKS"); ownerKeyStore.load(null, null); ownerKeyStore.setCertificateEntry("ownerEncCert", encCert); ownerKeyStore.setCertificateEntry("ownerSignCert", signCert); entry = new ZipArchiveEntry("ownerCerts.bks"); } baos = new ByteArrayOutputStream(); ownerKeyStore.store(baos, password); baos.flush(); data = baos.toByteArray(); entry.setSize(data.length); out.putArchiveEntry(entry); out.write(data); out.flush(); out.closeArchiveEntry(); out.flush(); out.close(); logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container finished."); return new PanboxFilePairingWriteReturnContainer(devicename, devCert, devType); }
From source file:net.firejack.platform.web.security.x509.KeyUtils.java
public static void add(File keystore, KeyPair pair, String domain) { if (keystore == null) { throw new IllegalArgumentException("Key Store file should not be null."); }/*from w w w. j a v a2 s. c o m*/ try { KeyStore ks = KeyStore.getInstance("JKS", "SUN"); if (keystore.exists()) { FileInputStream stream = new FileInputStream(keystore); ks.load(stream, SECRET); IOUtils.closeQuietly(stream); } else { ks.load(null, SECRET); } if (!ks.containsAlias(ALIAS)) { X509Certificate certificate = generateCertificate(domain, 1, pair); ks.setKeyEntry(ALIAS, pair.getPrivate(), SECRET, new Certificate[] { certificate }); FileOutputStream stream = new FileOutputStream(keystore); ks.store(stream, SECRET); IOUtils.closeQuietly(stream); } } catch (Throwable th) { logger.error("Failed to initialize key store"); throw new OpenFlameRuntimeException(th.getMessage(), th); } }
From source file:net.theblackchamber.crypto.util.KeystoreUtils.java
/** * Method which will generate a random AES key and add it to a keystore with * the entry name provided./*from ww w . ja va 2 s . c o m*/ * * @param config * Configuration for generation of key. * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws CertificateException * @throws IOException */ public static void generateAESSecretKey(KeyConfig config) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { if (config == null || config.getKeyStoreFile() == null || StringUtils.isEmpty(config.getKeyEntryName()) || config.getAlgorithm() == null) { throw new KeyStoreException("Missing parameters, unable to create keystore."); } SecureRandom random = new SecureRandom(); KeyGenerator keygen = KeyGenerator.getInstance(config.getAlgorithm().toString(), new BouncyCastleProvider()); keygen.init(config.getKeySize(), random); SecretKey key = keygen.generateKey(); KeyStore keyStore = KeyStore.getInstance("JCEKS"); FileInputStream fis = null; if (config.getKeyStoreFile().exists() && FileUtils.sizeOf(config.getKeyStoreFile()) > 0) { fis = new FileInputStream(config.getKeyStoreFile()); } keyStore.load(fis, config.getKeyStorePassword().toCharArray()); KeyStore.ProtectionParameter protectionParameter = new KeyStore.PasswordProtection( config.getKeyStorePassword().toCharArray()); KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(key); keyStore.setEntry(config.getKeyEntryName(), secretKeyEntry, protectionParameter); if (fis != null) { fis.close(); } FileOutputStream fos = new FileOutputStream(config.getKeyStoreFile()); keyStore.store(fos, config.getKeyStorePassword().toCharArray()); fos.close(); }
From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerTest.java
@org.junit.BeforeClass public static void setup() throws Exception { // Create keys String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE"; String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE"; // Create a truststore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, "security".toCharArray()); serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30), "sspass", "myservicekey", "skpass", keystore); clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass", "myclientkey", "ckpass", keystore); File truststoreFile = File.createTempFile("kafkatruststore", ".jks"); try (OutputStream output = new FileOutputStream(truststoreFile)) { keystore.store(output, "security".toCharArray()); }//from w ww . j av a2 s.c o m truststorePath = truststoreFile.getPath(); zkServer = new TestingServer(); // Get a random port ServerSocket serverSocket = new ServerSocket(0); port = serverSocket.getLocalPort(); serverSocket.close(); tempDir = Files.createTempDirectory("kafka"); final Properties props = new Properties(); props.put("broker.id", 1); props.put("host.name", "localhost"); props.put("port", port); props.put("log.dir", tempDir.toString()); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", Boolean.TRUE.toString()); // Enable SSL props.put("listeners", "SSL://localhost:" + port); props.put("ssl.keystore.location", serviceKeystorePath); props.put("ssl.keystore.password", "sspass"); props.put("ssl.key.password", "skpass"); props.put("ssl.truststore.location", truststorePath); props.put("ssl.truststore.password", "security"); props.put("security.inter.broker.protocol", "SSL"); props.put("ssl.client.auth", "required"); // Plug in Apache Ranger authorizer props.put("authorizer.class.name", "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer"); // Create users for testing UserGroupInformation.createUserForTesting(clientDN, new String[] { "public" }); UserGroupInformation.createUserForTesting(serviceDN, new String[] { "IT" }); KafkaConfig config = new KafkaConfig(props); kafkaServer = new KafkaServerStartable(config); kafkaServer.startup(); // Create some topics ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$); final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false); AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$); AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$); }
From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java
/** * Save a KeyStore to a file protected by a password. * * @param keyStore//from ww w. j a v a 2 s . c om * The KeyStore * @param keyStoreFile * The file to save the KeyStore to * @param password * The password to protect the KeyStore with * @throws CryptoException * Problem encountered saving the KeyStore * @throws FileNotFoundException * If the KeyStore file exists but is a directory rather than a * regular file, does not exist but cannot be created, or cannot * be opened for any other reason * @throws IOException * An I/O error occurred */ public static void save(KeyStore keyStore, File keyStoreFile, Password password) throws CryptoException, IOException { KeyStoreType keyStoreType = KeyStoreType.resolveJce(keyStore.getType()); if (!keyStoreType.isFileBased()) { throw new CryptoException(MessageFormat.format(res.getString("NoSaveKeyStoreNotFile.exception.message"), keyStoreType.jce())); } FileOutputStream fos = null; fos = new FileOutputStream(keyStoreFile); try { keyStore.store(fos, password.toCharArray()); } catch (IOException ex) { throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex); } catch (KeyStoreException ex) { throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex); } catch (CertificateException ex) { throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex); } catch (NoSuchAlgorithmException ex) { throw new CryptoException(res.getString("NoSaveKeyStore.exception.message"), ex); } finally { IOUtils.closeQuietly(fos); } }
From source file:com.cloud.utils.security.CertificateHelper.java
public static byte[] buildAndSaveKeystore(List<Ternary<String, String, String>> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, storePassword != null ? storePassword.toCharArray() : null); //name,cert,key for (Ternary<String, String, String> cert : certs) { if (cert.third() == null) { Certificate c = buildCertificate(cert.second()); ks.setCertificateEntry(cert.first(), c); } else {//w w w .j a v a2 s . com Certificate[] c = new Certificate[certs.size()]; int i = certs.size(); for (Ternary<String, String, String> ct : certs) { c[i - 1] = buildCertificate(ct.second()); i--; } ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c); } } ByteArrayOutputStream os = new ByteArrayOutputStream(); ks.store(os, storePassword != null ? storePassword.toCharArray() : null); os.close(); return os.toByteArray(); }
From source file:org.lockss.util.KeyStoreUtil.java
static void storeKeyStore(KeyStore keyStore, File keyStoreFile, String keyStorePassword) throws FileNotFoundException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {//from w w w.j a va 2s . c o m OutputStream outs = null; try { log.debug3("Storing KeyStore in " + keyStoreFile); outs = new BufferedOutputStream(new FileOutputStream(keyStoreFile)); keyStore.store(outs, keyStorePassword.toCharArray()); outs.close(); } finally { IOUtil.safeClose(outs); } }
From source file:org.nuxeo.common.codec.Crypto.java
/** * Store a key in a keystore.<br>// w w w. j a v a2 s . co m * The keystore is created if it doesn't exist. * * @param keystorePath Path to the keystore * @param keystorePass Keystore password * @param keyAlias Key alias prefix. It must be suffixed with the algorithm ({@link SecretKey#getAlgorithm()} is * fine). * @param keyPass Key password * @param key * @throws GeneralSecurityException * @throws IOException * @see #IMPLEMENTED_ALGOS */ public static void setKeyInKeyStore(String keystorePath, char[] keystorePass, String keyAlias, char[] keyPass, SecretKey key) throws GeneralSecurityException, IOException { KeyStore keystore = KeyStore.getInstance("JCEKS"); if (!new File(keystorePath).exists()) { log.info("Creating a new JCEKS keystore at " + keystorePath); keystore.load(null); } else { try (InputStream keystoreStream = new FileInputStream(keystorePath)) { keystore.load(keystoreStream, keystorePass); } } KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key); PasswordProtection keyPassword = new PasswordProtection(keyPass); keystore.setEntry(keyAlias, keyStoreEntry, keyPassword); try (OutputStream keystoreStream = new FileOutputStream(keystorePath)) { keystore.store(keystoreStream, keystorePass); } }
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 . *//*from w w w . j a va2 s. c om*/ 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); } } }