Java Code Examples for java.security.KeyStore#getInstance()

The following examples show how to use java.security.KeyStore#getInstance() . 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 File: JwtAuthenticatorTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testAuthenticateKeystoreECWebsite() throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getClass().getResourceAsStream("/keystore.jks"), "password".toCharArray());

    final Key privateKey = ks.getKey("trellis-ec", "password".toCharArray());
    final String token = Jwts.builder().setSubject("acoburn")
         .claim("website", "https://people.apache.org/~acoburn/#i")
         .signWith(privateKey, SignatureAlgorithm.ES256).compact();

    final Authenticator authenticator = new JwtAuthenticator(
            ks.getCertificate("trellis-ec").getPublicKey());

    final Principal p = authenticator.authenticate(token);
    assertNotNull(p, "Missing principal!");
    assertEquals("https://people.apache.org/~acoburn/#i", p.getName(), "Incorrect webid!");
}
 
Example 2
Source File: SSLUtil.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
public static void useCaCertificateValidation(String certificatePath) {
    try (InputStream is = new FileInputStream(certificatePath)) {

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        X509Certificate caCertificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                                                                            .generateCertificate(is);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry("caCert", caCertificate);

        trustManagerFactory.init(keyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagerFactory.getTrustManagers(), null);
        SSLContext.setDefault(context);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 3
Source File: CryptoHelper.java    From JPPF with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a keystore with a default password.
 * @param pwd default keystore password
 * @throws Exception if any error occurs.
 */
private static void generateKeyStore(final String pwd) throws Exception {
  final byte[] passwordBytes = pwd.getBytes();
  // encode the password in Base64
  final byte[] encodedBytes = Base64Encoding.encodeBytesToBytes(passwordBytes);
  // store the encoded password to a file
  try (final FileOutputStream fos = new FileOutputStream(getPasswordFilename())) {
    fos.write(encodedBytes);
    fos.flush();
  }
  final char[] password = pwd.toCharArray();
  final KeyStore ks = KeyStore.getInstance(getKeystoreProvider());
  // create an empty keystore
  ks.load(null, password);
  // generate the initial secret key
  final KeyGenerator gen = KeyGenerator.getInstance(getAlgorithm());
  final SecretKey key = gen.generateKey();
  // save the key in the keystore
  final KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key);
  ks.setEntry(getKeyAlias(), skEntry, new KeyStore.PasswordProtection(password));
  // save the keystore to a file
  try (final FileOutputStream fos = new FileOutputStream(getKeystoreFilename())) {
    ks.store(fos, password);
  }
}
 
Example 4
Source File: NewSize7.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String FILE = "newsize7-ks";
    new File(FILE).delete();
    sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
            FILE +
            " -alias a -dname cn=c -storepass changeit" +
            " -keypass changeit -keyalg rsa").split(" "));
    KeyStore ks = KeyStore.getInstance("JKS");
    try (FileInputStream fin = new FileInputStream(FILE)) {
        ks.load(fin, null);
    }
    Files.delete(Paths.get(FILE));
    RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
    if (r.getModulus().bitLength() != 2048) {
        throw new Exception("Bad keysize");
    }
    X509Certificate x = (X509Certificate)ks.getCertificate("a");
    if (!x.getSigAlgName().equals("SHA256withRSA")) {
        throw new Exception("Bad sigalg");
    }
}
 
Example 5
Source File: MetadataStoreLoadTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example 6
Source File: KeyStoreAdminClient.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public boolean isPrivateKeyStore(byte[] content, String password, String type)
        throws java.lang.Exception {
    try {
        boolean isPrivateStore = false;
        ByteArrayInputStream stream = new ByteArrayInputStream(content);
        KeyStore store = KeyStore.getInstance(type);
        store.load(stream, password.toCharArray());
        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String value = aliases.nextElement();
            if (store.isKeyEntry(value)) {
                isPrivateStore = true;
                break;
            }
        }
        return isPrivateStore;
    } catch (java.lang.Exception e) {
        log.error("Error in checking private key store.", e);
        throw e;
    }
}
 
Example 7
Source File: DefaultSignatureAlgorithm.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void run(String keyAlg, int keySize,
                String expectedSigAlg, String sigAlg) throws Exception {
    String alias = keyAlg + keySize + System.currentTimeMillis();
    String cmd = "-keystore ks -storepass changeit" +
            " -keypass changeit -alias " + alias +
            " -keyalg " + keyAlg + " -keysize " + keySize +
            " -genkeypair -dname CN=" + alias + " -debug";
    if (sigAlg != null) {
        cmd += " -sigalg " + sigAlg;
    }
    Main.main(cmd.split(" "));

    KeyStore ks = KeyStore.getInstance(
            new File("ks"), "changeit".toCharArray());
    X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
    String actualSigAlg = cert.getSigAlgName();
    if (!actualSigAlg.equals(expectedSigAlg)) {
        throw new Exception("Failure at " + alias + ": expected "
                + expectedSigAlg + ", actually " + actualSigAlg);
    }
}
 
Example 8
Source File: HttpsUtils.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
private static KeyManagerFactory getKeyManagerFactory(InputStream key, String keyPassword) {
    KeyManagerFactory kmf = null;

    try {
        String keyStoreType = "BKS";
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(key, keyPassword.toCharArray());

        String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
        kmf.init(keyStore, keyPassword.toCharArray());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return kmf;
}
 
Example 9
Source File: NewSize7.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String FILE = "newsize7-ks";
    new File(FILE).delete();
    sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
            FILE +
            " -alias a -dname cn=c -storepass changeit" +
            " -keypass changeit -keyalg rsa").split(" "));
    KeyStore ks = KeyStore.getInstance("JKS");
    try (FileInputStream fin = new FileInputStream(FILE)) {
        ks.load(fin, null);
    }
    Files.delete(Paths.get(FILE));
    RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
    if (r.getModulus().bitLength() != 2048) {
        throw new Exception("Bad keysize");
    }
    X509Certificate x = (X509Certificate)ks.getCertificate("a");
    if (!x.getSigAlgName().equals("SHA256withRSA")) {
        throw new Exception("Bad sigalg");
    }
}
 
Example 10
Source File: HttpsUtils.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a KeyStore from standard PEM files.
 * @param privateKeyPem the private key PEM file
 * @param certificatePem the certificate(s) PEM file
 * @param password to set to protect the private key
 */
public static KeyStore createKeyStore(InputStream certificatePem, InputStream privateKeyPem, final String password) throws Exception {
    final X509Certificate[] cert = createCertificates(certificatePem);
    final KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null);
    // Import private key
    PEMKeyPair pem = CertUtils.getPEM(privateKeyPem);
    boolean isGM = pem.getPrivateKeyInfo().getPrivateKeyAlgorithm().getParameters().toString().equals(SM2Priv.SM2OID);

    final PrivateKey key = CertUtils.getPrivateKeyFromPEM(pem, isGM);
    keystore.setKeyEntry("tlsCertPriv", key, password.toCharArray(), cert);
    return keystore;
}
 
Example 11
Source File: SSLUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
private static KeyManagerFactory getKeyManagerFactory(
		Configuration config,
		boolean internal,
		SslProvider provider)
		throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
		UnrecoverableKeyException {
	String keystoreFilePath = getAndCheckOption(
		config,
		internal ? SecurityOptions.SSL_INTERNAL_KEYSTORE : SecurityOptions.SSL_REST_KEYSTORE,
		SecurityOptions.SSL_KEYSTORE);

	String keystorePassword = getAndCheckOption(
		config,
		internal ? SecurityOptions.SSL_INTERNAL_KEYSTORE_PASSWORD : SecurityOptions.SSL_REST_KEYSTORE_PASSWORD,
		SecurityOptions.SSL_KEYSTORE_PASSWORD);

	String certPassword = getAndCheckOption(
		config,
		internal ? SecurityOptions.SSL_INTERNAL_KEY_PASSWORD : SecurityOptions.SSL_REST_KEY_PASSWORD,
		SecurityOptions.SSL_KEY_PASSWORD);

	KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	try (InputStream keyStoreFile = Files.newInputStream(new File(keystoreFilePath).toPath())) {
		keyStore.load(keyStoreFile, keystorePassword.toCharArray());
	}

	final KeyManagerFactory kmf;
	if (provider == OPENSSL || provider == OPENSSL_REFCNT) {
		kmf = new OpenSslX509KeyManagerFactory();
	} else {
		kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	}
	kmf.init(keyStore, certPassword.toCharArray());

	return kmf;
}
 
Example 12
Source File: HandshakeCompletedEventTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result.
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = Base64.decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}
 
Example 13
Source File: SslSocketFactory.java    From GreasySpoon with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load keystore information 
 * @param keyStoreName The keystore to read
 * @param keyStorePwd Keystore password
 * @return Keystore keystore object
 * @throws Exception
 */
public static KeyStore loadKeyStore(String keyStoreName, String keyStorePwd) throws Exception {
    KeyStore ks = KeyStore.getInstance(KEYSTORETYPE);
    // get user password and file input stream
    char[] password = keyStorePwd.toCharArray();
    java.io.FileInputStream fis = new java.io.FileInputStream(keyStoreName);
    ks.load(fis, password);
    fis.close();
    return ks;
}
 
Example 14
Source File: SecurityUtils.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the cacerts keystore with the configured CA certificates.
 */
public static KeyStore getCacertsKeyStore() throws Exception {
    File file = new File(getCacerts());
    if (!file.exists()) {
        return null;
    }

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try (FileInputStream fis = new FileInputStream(file)) {
        ks.load(fis, null);
    }
    return ks;
}
 
Example 15
Source File: RmiSslNoKeyStoreTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void checkKeystore(Properties props)
    throws IOException, GeneralSecurityException {
    if (log.isDebugOn())
        log.debug("checkKeystore","Checking Keystore configuration");

    final String keyStore =
        System.getProperty(PropertyNames.KEYSTORE);
    if (keyStore == null)
        throw new IllegalArgumentException("System property " +
                                           PropertyNames.KEYSTORE +
                                           " not specified");

    final String keyStorePass =
        System.getProperty(PropertyNames.KEYSTORE_PASSWD);
    if (keyStorePass == null) {
        // We don't have the password, we can only check whether the
        // file exists...
        //
        final File ksf = new File(keyStore);
        if (! ksf.canRead())
            throw new IOException(keyStore + ": not readable");

        if (log.isDebugOn())
            log.debug("checkSSL", "No password.");
        throw new IllegalArgumentException("System property " +
                                           PropertyNames.KEYSTORE_PASSWD +
                                           " not specified");
    }

    // Now we're going to load the keyStore - just to check it's
    // correct.
    //
    final String keyStoreType =
        System.getProperty(PropertyNames.KEYSTORE_TYPE,
                           KeyStore.getDefaultType());
    final KeyStore ks         = KeyStore.getInstance(keyStoreType);
    final FileInputStream fin = new FileInputStream(keyStore);
    final char keypassword[]  = keyStorePass.toCharArray();

    try {
        ks.load(fin,keypassword);
    } finally {
        Arrays.fill(keypassword,' ');
        fin.close();
    }

    if (log.isDebugOn())
        log.debug("checkSSL","SSL configuration successfully checked");
}
 
Example 16
Source File: RmiSslNoKeyStoreTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void checkKeystore(Properties props)
    throws IOException, GeneralSecurityException {
    if (log.isDebugOn())
        log.debug("checkKeystore","Checking Keystore configuration");

    final String keyStore =
        System.getProperty(PropertyNames.KEYSTORE);
    if (keyStore == null)
        throw new IllegalArgumentException("System property " +
                                           PropertyNames.KEYSTORE +
                                           " not specified");

    final String keyStorePass =
        System.getProperty(PropertyNames.KEYSTORE_PASSWD);
    if (keyStorePass == null) {
        // We don't have the password, we can only check whether the
        // file exists...
        //
        final File ksf = new File(keyStore);
        if (! ksf.canRead())
            throw new IOException(keyStore + ": not readable");

        if (log.isDebugOn())
            log.debug("checkSSL", "No password.");
        throw new IllegalArgumentException("System property " +
                                           PropertyNames.KEYSTORE_PASSWD +
                                           " not specified");
    }

    // Now we're going to load the keyStore - just to check it's
    // correct.
    //
    final String keyStoreType =
        System.getProperty(PropertyNames.KEYSTORE_TYPE,
                           KeyStore.getDefaultType());
    final KeyStore ks         = KeyStore.getInstance(keyStoreType);
    final FileInputStream fin = new FileInputStream(keyStore);
    final char keypassword[]  = keyStorePass.toCharArray();

    try {
        ks.load(fin,keypassword);
    } finally {
        Arrays.fill(keypassword,' ');
        fin.close();
    }

    if (log.isDebugOn())
        log.debug("checkSSL","SSL configuration successfully checked");
}
 
Example 17
Source File: SystemUtils.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public static KeyStore loadJKSKeyStore(String classPath, String password) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    InputStream is = SystemUtils.class.getClassLoader().getResourceAsStream(classPath);
    keyStore.load(is, password.toCharArray());
    return keyStore;
}
 
Example 18
Source File: IPAddressDNSIdentities.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 19
Source File: CertificateHelper.java    From PowerTunnel with MIT License 4 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority,
        String keyStoreType) throws NoSuchAlgorithmException,
        NoSuchProviderException, IOException,
        OperatorCreationException, CertificateException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, authority.commonName());
    nameBuilder.addRDN(BCStyle.O, authority.organization());
    nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
            | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore
            .getInstance(keyStoreType/* , PROVIDER_NAME */);
    result.load(null, null);
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), new Certificate[] { cert });
    return result;
}
 
Example 20
Source File: Basic.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static int signAlias(int testnum, String alias) throws Exception {

        if (ks == null) {
            ks = KeyStore.getInstance(KS_TYPE, provider);
            ks.load(null, tokenPwd);
        }

        if (alias == null) {
            Enumeration enu = ks.aliases();
            if (enu.hasMoreElements()) {
                alias = (String)enu.nextElement();
            }
        }

        PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
        if ("RSA".equals(pkey.getAlgorithm())) {
            System.out.println("got [" + alias + "] signing key: " + pkey);
        } else {
            throw new SecurityException
                ("expected RSA, got " + pkey.getAlgorithm());
        }

        Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
        s.initSign(pkey);
        System.out.println("initialized signature object with key");
        s.update("hello".getBytes());
        System.out.println("signature object updated with [hello] bytes");

        byte[] signed = s.sign();
        System.out.println("received signature " + signed.length +
                        " bytes in length");

        Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
        v.initVerify(ks.getCertificate(alias));
        v.update("hello".getBytes());
        v.verify(signed);
        System.out.println("signature verified");
        System.out.println("test " + testnum++ + " passed");

        return testnum;
    }