Java Code Examples for java.security.KeyStore#store()
The following examples show how to use
java.security.KeyStore#store() .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: incubator-tuweni File: SecurityTestUtils.java License: Apache License 2.0 | 6 votes |
static void configureJDKTrustStore(Path workDir, SelfSignedCertificate clientCert) throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readPemFile(new File(clientCert.privateKeyPath()).toPath())); PrivateKey clientPrivateKey = kf.generatePrivate(keysp); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate certificate = cf .generateCertificate( new ByteArrayInputStream(Files.readAllBytes(new File(clientCert.certificatePath()).toPath()))); ks.setCertificateEntry("clientCert", certificate); ks.setKeyEntry("client", clientPrivateKey, "changeit".toCharArray(), new Certificate[] {certificate}); Path tempKeystore = Files.createTempFile(workDir, "keystore", ".jks"); try (FileOutputStream output = new FileOutputStream(tempKeystore.toFile());) { ks.store(output, "changeit".toCharArray()); } System.setProperty("javax.net.ssl.trustStore", tempKeystore.toString()); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); }
Example 2
Source Project: mt-flume File: EncryptionTestUtils.java License: Apache License 2.0 | 6 votes |
public static void createKeyStore(File keyStoreFile, File keyStorePasswordFile, Map<String, File> keyAliasPassword) throws Exception { KeyStore ks = KeyStore.getInstance("jceks"); ks.load(null); List<String> keysWithSeperatePasswords = Lists.newArrayList(); for(String alias : keyAliasPassword.keySet()) { Key key = newKey(); char[] password = null; File passwordFile = keyAliasPassword.get(alias); if(passwordFile == null) { password = Files.toString(keyStorePasswordFile, Charsets.UTF_8) .toCharArray(); } else { keysWithSeperatePasswords.add(alias); password = Files.toString(passwordFile, Charsets.UTF_8).toCharArray(); } ks.setKeyEntry(alias, key, password, null); } char[] keyStorePassword = Files. toString(keyStorePasswordFile, Charsets.UTF_8).toCharArray(); FileOutputStream outputStream = new FileOutputStream(keyStoreFile); ks.store(outputStream, keyStorePassword); outputStream.close(); }
Example 3
Source Project: ariADDna File: KeyFactory.java License: Apache License 2.0 | 6 votes |
public void storeCertToKeyStore(File certFile, File keyStoreFile) throws KeyStoreException { try { X509CertImpl cert = (X509CertImpl) certFactory.getCertByFile(certFile); String alias = certFactory.getCertSubjectName(cert); LOGGER.info("Certificate with filename {} has Subject name {}", certFile.getAbsolutePath(), alias); FileInputStream fis = new FileInputStream(keyStoreFile); KeyStore keyStore = KeyStore.getInstance(KEYSTORE_FORMAT); keyStore.load(fis, pass); LOGGER.info("KeyStore load successful"); fis.close(); keyStore.setCertificateEntry(alias, cert); FileOutputStream fos = new FileOutputStream(keyStoreFile); keyStore.store(fos, pass); LOGGER.info("Certificate with filename {} stored in keyStore with filename {}", certFile.getAbsolutePath(), keyStoreFile.getAbsolutePath()); fos.close(); } catch (Exception e) { LOGGER.error("Exception: ", e); throw new KeyStoreException("Caused by: ", e); } }
Example 4
Source Project: blackduck-alert File: CertificateTestUtil.java License: Apache License 2.0 | 5 votes |
public void init(AlertProperties alertProperties) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStoreFile = new File(TRUSTSTORE_FILE_PATH); trustStoreFile.getParentFile().mkdirs(); trustStoreFile.createNewFile(); System.out.println(String.format("Trust store file path: %s", trustStoreFile.getAbsolutePath())); FileOutputStream outputStream = new FileOutputStream(trustStoreFile); trustStore.store(outputStream, TRUSTSTORE_PASSWORD.toCharArray()); outputStream.close(); alertProperties.getTrustStoreFile().ifPresent(file -> System.out.println(String.format("Alert Properties trust store file %s", file))); }
Example 5
Source Project: TencentKona-8 File: SmallPrimeExponentP.java License: GNU General Public License v2.0 | 5 votes |
public static void main(String argv[]) throws Exception { String osName = System.getProperty("os.name"); if (!osName.startsWith("Windows")) { System.out.println("Not windows"); return; } KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); CertAndKeyGen ckg = new CertAndKeyGen("RSA", "SHA1withRSA"); ckg.setRandom(new SecureRandom()); boolean see63 = false, see65 = false; while (!see63 || !see65) { ckg.generate(1024); RSAPrivateCrtKey k = (RSAPrivateCrtKey) ckg.getPrivateKey(); int len = k.getPrimeExponentP().toByteArray().length; if (len == 63 || len == 65) { if (len == 63) { if (see63) continue; else see63 = true; } if (len == 65) { if (see65) continue; else see65 = true; } System.err.print(len); ks.setKeyEntry("anything", k, null, new X509Certificate[]{ ckg.getSelfCertificate(new X500Name("CN=Me"), 1000) }); } System.err.print('.'); } ks.store(null, null); }
Example 6
Source Project: jdk8u_jdk File: P12SecretKey.java License: GNU General Public License v2.0 | 5 votes |
private void run(String keystoreType) throws Exception { char[] pw = "password".toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(null, pw); KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128); SecretKey key = kg.generateKey(); KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key); KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw); ks.setEntry(ALIAS, ske, kspp); File ksFile = File.createTempFile("test", ".test"); try (FileOutputStream fos = new FileOutputStream(ksFile)) { ks.store(fos, pw); fos.flush(); } // now see if we can get it back try (FileInputStream fis = new FileInputStream(ksFile)) { KeyStore ks2 = KeyStore.getInstance(keystoreType); ks2.load(fis, pw); KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp); SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey(); if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) { System.err.println("OK: worked just fine with " + keystoreType + " keystore"); } else { System.err.println("ERROR: keys are NOT equal after storing in " + keystoreType + " keystore"); } } }
Example 7
Source Project: alfresco-core File: AlfrescoKeyStoreImpl.java License: GNU Lesser General Public License v3.0 | 5 votes |
protected void createKey(String keyAlias) { KeyInfoManager keyInfoManager = null; try { keyInfoManager = getKeyInfoManager(getKeyStoreParameters()); Key key = getSecretKey(keyInfoManager.getKeyInformation(keyAlias)); encryptionKeysRegistry.registerKey(keyAlias, key); keys.setKey(keyAlias, key); KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager); ks.setKeyEntry(keyAlias, key, keyInfoManager.getKeyInformation(keyAlias).getPassword().toCharArray(), null); OutputStream keyStoreOutStream = getKeyStoreOutStream(); ks.store(keyStoreOutStream, keyInfoManager.getKeyStorePassword().toCharArray()); // Workaround for MNT-15005 keyStoreOutStream.close(); logger.info("Created key: " + keyAlias + "\n in key store: \n" + " Location: " + getKeyStoreParameters().getLocation() + "\n" + " Provider: " + getKeyStoreParameters().getProvider() + "\n" + " Type: " + getKeyStoreParameters().getType()); } catch(Throwable e) { throw new AlfrescoRuntimeException( "Failed to create key: " + keyAlias + "\n in key store: \n" + " Location: " + getKeyStoreParameters().getLocation() + "\n" + " Provider: " + getKeyStoreParameters().getProvider() + "\n" + " Type: " + getKeyStoreParameters().getType(), e); } finally { if(keyInfoManager != null) { keyInfoManager.clear(); } } }
Example 8
Source Project: openjdk-jdk8u-backup File: Utils.java License: GNU General Public License v2.0 | 5 votes |
public static void saveKeyStore(KeyStore ks, String file, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { try (FileOutputStream fout = new FileOutputStream(file)) { ks.store(fout, passwd); } }
Example 9
Source Project: big-c File: KeyStoreTestUtil.java License: Apache License 2.0 | 5 votes |
private static void saveKeyStore(KeyStore ks, String filename, String password) throws GeneralSecurityException, IOException { FileOutputStream out = new FileOutputStream(filename); try { ks.store(out, password.toCharArray()); } finally { out.close(); } }
Example 10
Source Project: nexus-public File: KeyStoreStorageImpl.java License: Eclipse Public License 1.0 | 5 votes |
@Override public void save(final KeyStore keyStore, final char[] password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(16 * 1024)) { keyStore.store(out, password); storage.save(keyStoreName, out); } }
Example 11
Source Project: hottub File: Utils.java License: GNU General Public License v2.0 | 5 votes |
public static void saveKeyStore(KeyStore ks, String file, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { try (FileOutputStream fout = new FileOutputStream(file)) { ks.store(fout, passwd); } }
Example 12
Source Project: Jumble File: JumbleCertificateGenerator.java License: GNU General Public License v3.0 | 5 votes |
public static X509Certificate generateCertificate(OutputStream output) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, KeyStoreException, NoSuchProviderException, IOException { BouncyCastleProvider provider = new BouncyCastleProvider(); // Use SpongyCastle provider, supports creating X509 certs KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048, new SecureRandom()); KeyPair keyPair = generator.generateKeyPair(); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(provider).build(keyPair.getPrivate()); Date startDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.YEAR, YEARS_VALID); Date endDate = calendar.getTime(); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(ISSUER), BigInteger.ONE, startDate, endDate, new X500Name(ISSUER), publicKeyInfo); X509CertificateHolder certificateHolder = certBuilder.build(signer); X509Certificate certificate = new JcaX509CertificateConverter().setProvider(provider).getCertificate(certificateHolder); KeyStore keyStore = KeyStore.getInstance("PKCS12", provider); keyStore.load(null, null); keyStore.setKeyEntry("Jumble Key", keyPair.getPrivate(), null, new X509Certificate[] { certificate }); keyStore.store(output, "".toCharArray()); return certificate; }
Example 13
Source Project: xipki File: Actions.java License: Apache License 2.0 | 5 votes |
@Override protected Object execute0() throws Exception { File realKsFile = new File(IoUtil.expandFilepath(ksFile)); KeyStore ks = KeyStore.getInstance(ksType); char[] password = readPasswordIfNotSet(ksPwd); Set<String> aliases = new HashSet<>(10); if (realKsFile.exists()) { InputStream inStream = Files.newInputStream(realKsFile.toPath()); try { ks.load(inStream, password); } finally { inStream.close(); } Enumeration<String> strs = ks.aliases(); while (strs.hasMoreElements()) { aliases.add(strs.nextElement()); } } else { ks.load(null); } for (String certFile : certFiles) { X509Cert cert = X509Util.parseCert(new File(certFile)); String baseAlias = X509Util.getCommonName(cert.getSubject()); String alias = baseAlias; int idx = 2; while (aliases.contains(alias)) { alias = baseAlias + "-" + (idx++); } ks.setCertificateEntry(alias, cert.toJceCert()); aliases.add(alias); } ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); ks.store(bout, password); saveVerbose("saved keystore to file", realKsFile, bout.toByteArray()); return null; }
Example 14
Source Project: vault-crd File: SharedVaultResponseMapper.java License: Apache License 2.0 | 4 votes |
VaultSecret mapJks(VaultResponseData data, VaultJKSConfiguration jksConfiguration, VaultType type) throws SecretNotAccessibleException { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null, getPassword(jksConfiguration).toCharArray()); Certificate[] publicKeyList = getPublicKey(data.getCertificate()); keyStore.setKeyEntry( getAlias(jksConfiguration), getPrivateKey(data.getPrivate_key()), getPassword(jksConfiguration).toCharArray(), publicKeyList); if (jksConfiguration != null && !StringUtils.isEmpty(jksConfiguration.getCaAlias())) { keyStore.setCertificateEntry( jksConfiguration.getCaAlias(), getPublicKey(data.getIssuing_ca())[0] ); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); keyStore.store(outputStream, getPassword(jksConfiguration).toCharArray()); String b64KeyStore = Base64.getEncoder().encodeToString(outputStream.toByteArray()); HashMap<String, String> secretData = new HashMap<String, String>() {{ put(getKey(jksConfiguration), b64KeyStore); }}; String compare; if (type.equals(VaultType.CERTJKS)) { String base64Cert = Base64.getEncoder().encodeToString(data.getCertificate().getBytes()); String base64Key = Base64.getEncoder().encodeToString(data.getPrivate_key().getBytes()); compare = Sha256.generateSha256(base64Cert, base64Key); } else { // VaultType.PKIJKS X509Certificate compareCert = getCertificateWithShortestLivetime(publicKeyList); SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT); TimeZone tz = TimeZone.getTimeZone("UTC"); dateFormat.setTimeZone(tz); compare = dateFormat.format(compareCert.getNotAfter()); } return new VaultSecret(secretData, compare); } catch (IOException | GeneralSecurityException e) { throw new SecretNotAccessibleException("Couldn't generate keystore", e); } }
Example 15
Source Project: jdk8u-jdk File: TestKeyStoreEntry.java License: GNU General Public License v2.0 | 4 votes |
public void runTest(Provider p) throws Exception { try (FileOutputStream fos = new FileOutputStream("jceks"); FileInputStream fis = new FileInputStream("jceks");) { KeyStore ks = KeyStore.getInstance("jceks", p); // create an empty key store ks.load(null, null); // store the secret keys String aliasHead = new String("secretKey"); for (int j = 0; j < NUM_ALGOS; j++) { ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null); } // write the key store out to a file ks.store(fos, PASSWDF); // wipe clean the existing key store for (int k = 0; k < NUM_ALGOS; k++) { ks.deleteEntry(aliasHead + k); } if (ks.size() != 0) { throw new RuntimeException("ERROR: re-initialization failed"); } // reload the key store with the file ks.load(fis, PASSWDF); // check the integrity/validaty of the key store Key temp = null; String alias = null; if (ks.size() != NUM_ALGOS) { throw new RuntimeException("ERROR: wrong number of key" + " entries"); } for (int m = 0; m < ks.size(); m++) { alias = aliasHead + m; temp = ks.getKey(alias, PASSWDK); // compare the keys if (!temp.equals(sks[m])) { throw new RuntimeException("ERROR: key comparison (" + m + ") failed"); } // check the type of key if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) { throw new RuntimeException("ERROR: type identification (" + m + ") failed"); } } } }
Example 16
Source Project: openjdk-jdk8u-backup File: PKCS12SameKeyId.java License: GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { // Prepare a JKS keystore with many entries new File(JKSFILE).delete(); for (int i=0; i<SIZE; i++) { System.err.print("."); String cmd = "-keystore " + JKSFILE + " -storepass changeit -keypass changeit -keyalg rsa " + "-genkeypair -alias p" + i + " -dname CN=" + i; sun.security.tools.keytool.Main.main(cmd.split(" ")); } // Prepare EncryptedPrivateKeyInfo parameters, copied from various // places in PKCS12KeyStore.java AlgorithmParameters algParams = AlgorithmParameters.getInstance("PBEWithSHA1AndDESede"); algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024)); AlgorithmId algid = new AlgorithmId( new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams); PBEKeySpec keySpec = new PBEKeySpec(PASSWORD); SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); SecretKey skey = skFac.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede"); cipher.init(Cipher.ENCRYPT_MODE, skey, algParams); // Pre-calculated keys and certs and aliases byte[][] keys = new byte[SIZE][]; Certificate[][] certChains = new Certificate[SIZE][]; String[] aliases = new String[SIZE]; // Reads from JKS keystore and pre-calculate KeyStore ks = KeyStore.getInstance("jks"); try (FileInputStream fis = new FileInputStream(JKSFILE)) { ks.load(fis, PASSWORD); } for (int i=0; i<SIZE; i++) { aliases[i] = "p" + i; byte[] enckey = cipher.doFinal( ks.getKey(aliases[i], PASSWORD).getEncoded()); keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded(); certChains[i] = ks.getCertificateChain(aliases[i]); } // Write into PKCS12 keystore. Use this overloaded version of // setKeyEntry() to be as fast as possible, so that they would // have same localKeyId. KeyStore p12 = KeyStore.getInstance("pkcs12"); p12.load(null, PASSWORD); for (int i=0; i<SIZE; i++) { p12.setKeyEntry(aliases[i], keys[i], certChains[i]); } try (FileOutputStream fos = new FileOutputStream(P12FILE)) { p12.store(fos, PASSWORD); } // Check private keys still match certs p12 = KeyStore.getInstance("pkcs12"); try (FileInputStream fis = new FileInputStream(P12FILE)) { p12.load(fis, PASSWORD); } for (int i=0; i<SIZE; i++) { String a = "p" + i; X509Certificate x = (X509Certificate)p12.getCertificate(a); X500Name name = (X500Name)x.getSubjectDN(); if (!name.getCommonName().equals(""+i)) { throw new Exception(a + "'s cert is " + name); } } }
Example 17
Source Project: wildfly-core File: KeyStoresTestCase.java License: GNU Lesser General Public License v2.1 | 4 votes |
private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile) throws Exception { try (FileOutputStream fos = new FileOutputStream(outputFile)){ keyStore.store(fos, KEYSTORE_PASSWORD); } }
Example 18
Source Project: testarea-itext5 File: KeyAlgorithmName.java License: GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/33788331/why-does-key-getalgorithm-return-a-different-result-after-saving-and-reloading-t"> * Why does Key.getAlgorithm return a different result after saving and reloading the KeyStore * </a> * <p> * Just as the OP claims, the first output is "ECDSA", the second "EC". * </p> */ @Test public void testNameChangeAfterReload() throws GeneralSecurityException, IOException { String PROVIDER = "BC"; String KEY_ALGORITHM = "ECDSA"; String SIGNATURE_ALGORITHM = "SHA1WITHECDSA"; String ALIAS = "TestAlias"; char [] PASSWORD = "password".toCharArray(); String KEYSTORE = "c:/temp/keystore.p12"; Security.addProvider(new BouncyCastleProvider()); // Generate the key Calendar calNow = Calendar.getInstance(); Calendar calLater = Calendar.getInstance(); calLater.set(Calendar.YEAR, calLater.get(Calendar.YEAR) + 25); Date startDate = new Date(calNow.getTimeInMillis()); Date expiryDate = new Date(calLater.getTimeInMillis()); ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp192r1"); KeyPairGenerator g = KeyPairGenerator.getInstance(KEY_ALGORITHM, PROVIDER); g.initialize(ecSpec, new SecureRandom()); KeyPair keyPair = g.generateKeyPair(); X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal("CN=Test"); certGen.setSerialNumber(new BigInteger(8, new SecureRandom())); certGen.setIssuerDN(dnName); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(SIGNATURE_ALGORITHM); X509Certificate cert = certGen.generate(keyPair.getPrivate(), PROVIDER); // Save the keystore KeyStore exportStore = KeyStore.getInstance("PKCS12", PROVIDER); exportStore.load(null, null); exportStore.setKeyEntry(ALIAS, keyPair.getPrivate(), PASSWORD, new Certificate[] { cert }); FileOutputStream out = new FileOutputStream(KEYSTORE); exportStore.store(out, PASSWORD); out.flush(); out.close(); // print the info from the keystore Key keyA = exportStore.getKey(ALIAS, PASSWORD); System.out.println(keyA.getAlgorithm()); // Reload the keystore FileInputStream in = new FileInputStream(KEYSTORE); exportStore.load(in, PASSWORD); in.close(); // print the info from the reloaded keystore Key keyB = exportStore.getKey(ALIAS, PASSWORD); System.out.println(keyB.getAlgorithm()); }
Example 19
Source Project: dragonwell8_jdk File: PKCS12SameKeyId.java License: GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { // Prepare a JKS keystore with many entries new File(JKSFILE).delete(); for (int i=0; i<SIZE; i++) { System.err.print("."); String cmd = "-keystore " + JKSFILE + " -storepass changeit -keypass changeit -keyalg rsa " + "-genkeypair -alias p" + i + " -dname CN=" + i; sun.security.tools.keytool.Main.main(cmd.split(" ")); } // Prepare EncryptedPrivateKeyInfo parameters, copied from various // places in PKCS12KeyStore.java AlgorithmParameters algParams = AlgorithmParameters.getInstance("PBEWithSHA1AndDESede"); algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024)); AlgorithmId algid = new AlgorithmId( new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams); PBEKeySpec keySpec = new PBEKeySpec(PASSWORD); SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); SecretKey skey = skFac.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede"); cipher.init(Cipher.ENCRYPT_MODE, skey, algParams); // Pre-calculated keys and certs and aliases byte[][] keys = new byte[SIZE][]; Certificate[][] certChains = new Certificate[SIZE][]; String[] aliases = new String[SIZE]; // Reads from JKS keystore and pre-calculate KeyStore ks = KeyStore.getInstance("jks"); try (FileInputStream fis = new FileInputStream(JKSFILE)) { ks.load(fis, PASSWORD); } for (int i=0; i<SIZE; i++) { aliases[i] = "p" + i; byte[] enckey = cipher.doFinal( ks.getKey(aliases[i], PASSWORD).getEncoded()); keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded(); certChains[i] = ks.getCertificateChain(aliases[i]); } // Write into PKCS12 keystore. Use this overloaded version of // setKeyEntry() to be as fast as possible, so that they would // have same localKeyId. KeyStore p12 = KeyStore.getInstance("pkcs12"); p12.load(null, PASSWORD); for (int i=0; i<SIZE; i++) { p12.setKeyEntry(aliases[i], keys[i], certChains[i]); } try (FileOutputStream fos = new FileOutputStream(P12FILE)) { p12.store(fos, PASSWORD); } // Check private keys still match certs p12 = KeyStore.getInstance("pkcs12"); try (FileInputStream fis = new FileInputStream(P12FILE)) { p12.load(fis, PASSWORD); } for (int i=0; i<SIZE; i++) { String a = "p" + i; X509Certificate x = (X509Certificate)p12.getCertificate(a); X500Name name = (X500Name)x.getSubjectDN(); if (!name.getCommonName().equals(""+i)) { throw new Exception(a + "'s cert is " + name); } } }
Example 20
Source Project: deskcon-android File: MainActivity.java License: GNU General Public License v3.0 | 4 votes |
@Override protected Void doInBackground(Void... arg0) { Log.d("Cert Gen: ", "begin to generate"); try { // gen the RSA keypair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048, new SecureRandom()); KeyPair KPair = keyPairGenerator.generateKeyPair(); // generate Certificate X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); BigInteger serial = BigInteger.valueOf(new SecureRandom().nextInt()); String devicename = sharedPrefs.getString("device_name", "Device"); String deviceuuid = sharedPrefs.getString("uuid", "000000001111111"); v3CertGen.setSerialNumber(serial.abs()); v3CertGen.setIssuerDN(new X509Principal("CN=" + deviceuuid+"/" +devicename + ", OU=None, O=None L=None, C=None")); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10))); v3CertGen.setSubjectDN(new X509Principal("CN=" + deviceuuid+"/" +devicename + ", OU=None, O=None L=None, C=None")); v3CertGen.setPublicKey(KPair.getPublic()); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate PKCertificate = v3CertGen.generate(KPair.getPrivate()); // create keystore InputStream keyStoreStream = getResources().openRawResource(R.raw.defaultkeystore); KeyStore MyKeyStore = KeyStore.getInstance("BKS"); MyKeyStore.load(keyStoreStream, "android".toCharArray()); Certificate[] certchain = new Certificate[1]; certchain[0] = PKCertificate; PrivateKey privkey = KPair.getPrivate(); MyKeyStore.setKeyEntry("mykeypair",privkey, "passwd".toCharArray(), certchain); // write new Keystore OutputStream output = openFileOutput("devicekeystore.bks", Context.MODE_PRIVATE); MyKeyStore.store(output, "android".toCharArray()); output.close(); } catch (Exception e) { e.printStackTrace(); } return null; }