Java Code Examples for java.security.KeyStore.store()

The following are Jave code examples for showing how to use store() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-core   File: AlfrescoKeyStoreImpl.java   View Source Code Vote up 6 votes
protected void createKey(String keyAlias)
{
    KeyInfoManager keyInfoManager = null;

    try
    {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        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 2
Project: NBANDROID-V2   File: ApkUtils.java   View Source Code Vote up 6 votes
public static boolean addNewKey(KeyStore ks, File storeFile, char[] storePassword, DN dn) {
    try {
        Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
        ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
        FileOutputStream fos = new FileOutputStream(storeFile);
        boolean threw = true;
        try {
            ks.store(fos, storePassword);
            threw = false;
        } finally {
            Closeables.close(fos, threw);
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
        return false;
    }
    return true;
}
 
Example 3
Project: vrops-export   File: CertUtils.java   View Source Code Vote up 6 votes
public static void storeCert(X509Certificate cert, String filename, String password) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
	filename = getActualTruststoreFilename(filename);
	String alias = getThumbprint(cert, false);
	if(password == null)
		password = "changeit";
	KeyStore ks = loadExtendedTrust(filename, password);
	if(ks == null) {
		ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(null, password.toCharArray());
	}
	ks.setCertificateEntry(alias, cert);
	File f = new File(filename);
	File dir = f.getParentFile();
	if(dir !=null && !dir.exists())
		dir.mkdirs();
	OutputStream os = new FileOutputStream(filename);
	try {
		ks.store(os, password.toCharArray());
	} finally {
		os.close();
	}
}
 
Example 4
Project: ditb   File: KeyStoreTestUtil.java   View Source Code Vote up 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 5
Project: openjdk-jdk10   File: P12SecretKey.java   View Source Code Vote up 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 6
Project: pyplyn   File: AbstractRemoteClientTest.java   View Source Code Vote up 5 votes
@Test
public void testClientWithMutualAuthentication() throws Exception {
    Path tempFile = Files.createTempFile("keystore", ".jks");
    try {
        // ARRANGE
        final String keystorePassword = "password";

        connector = ImmutableConnector.builder().from(connector)
                .keystorePath(tempFile.toString())
                .keystorePassword(keystorePassword.getBytes(Charset.defaultCharset()))
                .build();

        // create a keystore
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(null, keystorePassword.toCharArray());

        // export the keystore to the temp file
        OutputStream os = Files.newOutputStream(tempFile);
        keystore.store(os, keystorePassword.toCharArray());
        os.close();

        // ACT
        client = new AbstractRemoteClientImpl(connector, AbstractRemoteClientImpl.RetroService.class);

    } finally {
        Files.delete(tempFile);
    }
}
 
Example 7
Project: xitk   File: P12KeyGenerator.java   View Source Code Vote up 5 votes
private static P12KeyGenerationResult generateIdentity(KeyPairWithSubjectPublicKeyInfo kp,
        KeystoreGenerationParameters params, String selfSignedCertSubject) throws Exception {
    Date now = new Date();
    Date notBefore = new Date(now.getTime() - 10 * MIN); // 10 minutes past
    Date notAfter = new Date(notBefore.getTime() + 3650 * DAY);

    String dnStr = (selfSignedCertSubject == null) ? "CN=DUMMY" : selfSignedCertSubject;
    X500Name subjectDn = new X500Name(dnStr);
    SubjectPublicKeyInfo subjectPublicKeyInfo = kp.subjectPublicKeyInfo();
    ContentSigner contentSigner = getContentSigner(kp.kypair().getPrivate());

    // Generate keystore
    X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn,
            BigInteger.valueOf(1), notBefore, notAfter, subjectDn, subjectPublicKeyInfo);

    KeyAndCertPair identity = new KeyAndCertPair(certGenerator.build(contentSigner),
            kp.kypair().getPrivate());

    KeyStore ks = KeyUtil.getKeyStore("PKCS12");
    ks.load(null, params.password());

    ks.setKeyEntry("main", identity.key(), params.password(),
            new Certificate[]{identity.jceCert()});

    ByteArrayOutputStream ksStream = new ByteArrayOutputStream();
    try {
        ks.store(ksStream, params.password());
    } finally {
        ksStream.flush();
    }

    P12KeyGenerationResult result = new P12KeyGenerationResult(ksStream.toByteArray());
    result.setKeystoreObject(ks);
    return result;
}
 
Example 8
Project: xitk   File: ImportCertCmd.java   View Source Code Vote up 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()) {
        FileInputStream inStream = new FileInputStream(realKsFile);
        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) {
        X509Certificate cert = X509Util.parseCert(certFile);
        String baseAlias = X509Util.getCommonName(cert.getSubjectX500Principal());
        String alias = baseAlias;
        int idx = 2;
        while (aliases.contains(alias)) {
            alias = baseAlias + "-" + (idx++);
        }
        ks.setCertificateEntry(alias, cert);
        aliases.add(alias);
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    ks.store(bout, password);
    saveVerbose("saved keystore to file", realKsFile, bout.toByteArray());
    return null;
}
 
Example 9
Project: xitk   File: ConvertKeystoreCmd.java   View Source Code Vote up 5 votes
@Override
protected Object execute0() throws Exception {
    File realInFile = new File(IoUtil.expandFilepath(inFile));
    File realOutFile = new File(IoUtil.expandFilepath(outFile));

    if (CompareUtil.equalsObject(realInFile, realOutFile)) {
        throw new IllegalCmdParamException("in and out cannot be the same");
    }

    KeyStore inKs = KeyStore.getInstance(inType);
    KeyStore outKs = KeyStore.getInstance(outType);
    outKs.load(null);

    char[] inPassword = readPasswordIfNotSet("password of the source keystore", inPwd);
    FileInputStream inStream = new FileInputStream(realInFile);
    try {
        inKs.load(inStream, inPassword);
    } finally {
        inStream.close();
    }

    char[] outPassword = readPasswordIfNotSet("password of the destination keystore", outPwd);
    Enumeration<String> aliases = inKs.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (inKs.isKeyEntry(alias)) {
            Certificate[] certs = inKs.getCertificateChain(alias);
            Key key = inKs.getKey(alias, inPassword);
            outKs.setKeyEntry(alias, key, outPassword, certs);
        } else {
            Certificate cert = inKs.getCertificate(alias);
            outKs.setCertificateEntry(alias, cert);
        }
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    outKs.store(bout, outPassword);
    saveVerbose("saved destination keystore to file", realOutFile, bout.toByteArray());
    return null;
}
 
Example 10
Project: jdk8u-jdk   File: TestKeyStoreEntry.java   View Source Code Vote up 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 11
Project: alfresco-core   File: AlfrescoKeyStoreImpl.java   View Source Code Vote up 4 votes
protected void createKeyStore(KeyStoreParameters keyStoreParameters, KeyMap keys)
    {
        KeyInfoManager keyInfoManager = null;

        try
        {
            if(!keyStoreExists(keyStoreParameters.getLocation()))
            {
                keyInfoManager = getKeyInfoManager(keyStoreParameters.getKeyMetaDataFileLocation());
                KeyStore ks = initialiseKeyStore(keyStoreParameters.getType(), keyStoreParameters.getProvider());
    
                String keyStorePassword = keyInfoManager.getKeyStorePassword();
                if(keyStorePassword == null)
                {
                    throw new AlfrescoRuntimeException("Key store password is null for keystore at location "
                            + getKeyStoreParameters().getLocation()
                            + ", key store meta data location" + getKeyMetaDataFileLocation());
                }

                for(String keyAlias : keys.getKeyAliases())
                {
                    KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias);

                    Key key = keys.getKey(keyAlias);
                    if(key == null)
                    {
                        logger.warn("Key with alias " + keyAlias + " is null when creating keystore at location " + keyStoreParameters.getLocation());
                    }
                    else
                    {
                        ks.setKeyEntry(keyAlias, key, keyInfo.getPassword().toCharArray(), null);
                    }
                }

//                try
//                {
//                    throw new Exception("Keystore creation: " + );
//                }
//                catch(Throwable e)
//                {
//                    logger.debug(e.getMessage());
//                    e.printStackTrace();
//                }

                OutputStream keyStoreOutStream = getKeyStoreOutStream();
                ks.store(keyStoreOutStream, keyStorePassword.toCharArray());
                // Workaround for MNT-15005
                keyStoreOutStream.close();
            }
            else
            {
                logger.warn("Can't create key store " + keyStoreParameters.getLocation() + ", already exists.");
            }
        }
        catch(Throwable e)
        {
            throw new AlfrescoRuntimeException(
                    "Failed to create keystore: \n" +
                    "   Location: " + keyStoreParameters.getLocation() + "\n" +
                    "   Provider: " + keyStoreParameters.getProvider() + "\n" +
                    "   Type:     " + keyStoreParameters.getType(),
                    e);
        }
        finally
        {
            if(keyInfoManager != null)
            {
                keyInfoManager.clear();
            }
        }
    }
 
Example 12
Project: ats-framework   File: SslUtils.java   View Source Code Vote up 4 votes
/**
 * Create keystore file 
 * 
 * @param cert the needed certificate for creating the keystore
 * @param host the host name. If not null it is appended to keystore file name
 * @param databaseName the database name. If not null it is appended to keystore file name
 * @param keyStoreFullPath the full path where the keystore file will be located
 * @param keyStoreType the type of the keystore file
 * @param keyStorePassword the the password for the keystore
 * 
 * TIP: if the keystoreFullPath, keyStoreType, keyStorePassword are empty we will set the default
 * 
 * @return Properties object with the keyStore location, type and password
 */
public synchronized static Properties createKeyStore(
                                                      Certificate cert,
                                                      String host,
                                                      String databaseName,
                                                      String keyStoreFullPath,
                                                      String keyStoreType,
                                                      String keyStorePassword ) {

    if (StringUtils.isNullOrEmpty(keyStoreType) && StringUtils.isNullOrEmpty(keyStorePassword)
        && StringUtils.isNullOrEmpty(keyStoreFullPath)) {
        // all parameters are empty
        keyStoreFullPath = System.getProperty("java.io.tmpdir") + "ats_TempKeyStore_" + host + "_"
                           + databaseName + ".jks";
        keyStorePassword = "password";
        keyStoreType = "JKS";
    } else if (StringUtils.isNullOrEmpty(keyStoreType) || StringUtils.isNullOrEmpty(keyStorePassword)
               || StringUtils.isNullOrEmpty(keyStoreFullPath)) {
        // at least one parameter is empty
        throw new IllegalArgumentException("All keystore parameters should be not be empty!");
    }
    Properties props = new Properties();
    if (!availableKeyStores.contains(keyStoreFullPath)) {
        try (FileOutputStream fos = new FileOutputStream(keyStoreFullPath)) {
            KeyStore ks = KeyStore.getInstance(keyStoreType);

            // create the keystore file
            ks.load(null, keyStorePassword.toCharArray());
            ks.setCertificateEntry("certificate", cert);
            ks.store(fos, keyStorePassword.toCharArray());
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException("No keystore was created!", e);
        }
        availableKeyStores.add(keyStoreFullPath);
    }
    props.put(OracleKeys.KEY_STORE_FULL_PATH, keyStoreFullPath);
    props.put(OracleKeys.KEY_STORE_TYPE, keyStoreType);
    props.put(OracleKeys.KEY_STORE_PASSWORD, keyStorePassword);

    return props;
}
 
Example 13
Project: jdk8u-jdk   File: PKCS12SameKeyId.java   View Source Code Vote up 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 14
Project: jdk8u-jdk   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void test(Certificate certs[], String inKeyStorePath,
        String userAlias, String outStorePass, String outKeyPass)
        throws KeyStoreException, NoSuchProviderException, IOException,
        CertificateException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    // init output key store
    KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
    outputKeyStore.load(null, null);
    try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need
        // decode first.
        byte[] input = Files.readAllBytes(Paths.get(CERT_PATH,
                inKeyStorePath));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        // input key store
        KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE,
                IN_KEYSTORE_PRV);
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        // add key/certificate to output key store
        Key key = inputKeyStore
                .getKey(userAlias, IN_KEY_PASS.toCharArray());
        out.println("Input Key Algorithm " + key.getAlgorithm());
        out.println("====Input Certs=====");
        if (certs == null) {
            certs = new Certificate[] { inputKeyStore
                    .getCertificate(userAlias) };
        }
        for (Certificate cert : certs) {
            out.println(((X509Certificate) cert).getSubjectDN());
        }
        outputKeyStore.setKeyEntry(userAlias, key,
                outKeyPass.toCharArray(), certs);
        Certificate retCerts[] = outputKeyStore
                .getCertificateChain(userAlias);
        out.println("====Output Certs=====");
        for (Certificate retCert : retCerts) {
            out.println(((X509Certificate) retCert).getSubjectDN());
        }
        out.println("====Output Key Algorithm=====");
        Key outKey = outputKeyStore.getKey(userAlias,
                outKeyPass.toCharArray());
        out.println(outKey.getAlgorithm());

        if (!key.equals(outKey)) {
            throw new RuntimeException("key don't match");
        }
        if (!Arrays.equals(certs, retCerts)) {
            throw new RuntimeException("certs don't match");
        }
        // save output
        outputKeyStore.store(fout, outStorePass.toCharArray());
        // test output
        testKeyStore(outputKeyStore, outKeyPass.toCharArray());
    }
}
 
Example 15
Project: jdk8u-jdk   File: SmallPrimeExponentP.java   View Source Code Vote up 4 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 16
Project: oscm   File: APPlatformServiceBeanIT.java   View Source Code Vote up 4 votes
@Test
public void testCheckToken() throws Exception {

    CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
    gen.generate(1024);
    X509Certificate cert = gen.getSelfCertificate(new X500Name("CN=ROOT"),
            new Date(), 10000000);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    String alias = "temp";
    String loc = "./temp.jks";
    String password = "changeit";
    ks.load(null, password.toCharArray());

    ks.setCertificateEntry(alias, cert);

    FileOutputStream fos = new FileOutputStream(loc);
    ks.store(fos, password.toCharArray());
    fos.close();

    Mockito.when(configSvc.getProxyConfigurationSetting(
            PlatformConfigurationKey.APP_TRUSTSTORE)).thenReturn(loc);
    Mockito.when(configSvc.getProxyConfigurationSetting(
            PlatformConfigurationKey.APP_TRUSTSTORE_PASSWORD))
            .thenReturn(password);
    Mockito.when(configSvc.getProxyConfigurationSetting(
            PlatformConfigurationKey.APP_TRUSTSTORE_BSS_ALIAS))
            .thenReturn(alias);

    String token = UUID.randomUUID().toString();

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(token.getBytes(StandardCharsets.UTF_8));
    byte[] tokenHash = md.digest();

    Key key = gen.getPrivateKey();
    Cipher c = Cipher.getInstance(key.getAlgorithm());
    c.init(Cipher.ENCRYPT_MODE, key);

    String tokenSignature = Base64
            .encodeBase64URLSafeString(c.doFinal(tokenHash));

    boolean check = platformSvc.checkToken(token, tokenSignature);

    assertTrue(check);

    Files.delete(new File(loc).toPath());
}
 
Example 17
Project: oscm   File: MySubscriptionsCtrlTest.java   View Source Code Vote up 4 votes
@Test
public void testCustomerTabURL() throws Exception {
    CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
    gen.generate(1024);
    X509Certificate cert = gen.getSelfCertificate(new X500Name("CN=ROOT"),
            new Date(), 10000000);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    String alias = "temp123";
    String loc = "./temp.jks";
    String password = "changeit";
    ks.load(null, password.toCharArray());

    ks.setKeyEntry(alias, gen.getPrivateKey(), password.toCharArray(),
            new Certificate[] { cert });

    FileOutputStream fos = new FileOutputStream(loc);
    ks.store(fos, password.toCharArray());
    fos.close();

    VOConfigurationSetting settingLoc = new VOConfigurationSetting();
    settingLoc.setValue(loc);
    Mockito.when(configSvc.getVOConfigurationSetting(
            ConfigurationKey.SSO_SIGNING_KEYSTORE,
            Configuration.GLOBAL_CONTEXT)).thenReturn(settingLoc);

    VOConfigurationSetting settingPwd = new VOConfigurationSetting();
    settingPwd.setValue(password);
    Mockito.when(configSvc.getVOConfigurationSetting(
            ConfigurationKey.SSO_SIGNING_KEYSTORE_PASS,
            Configuration.GLOBAL_CONTEXT)).thenReturn(settingPwd);

    VOConfigurationSetting settingAlias = new VOConfigurationSetting();
    settingAlias.setValue(alias);
    Mockito.when(configSvc.getVOConfigurationSetting(
            ConfigurationKey.SSO_SIGNING_KEY_ALIAS,
            Configuration.GLOBAL_CONTEXT)).thenReturn(settingAlias);

    String instId = "instance";
    String orgId = "organization";
    String subId = "subscription";
    String path = "http://abc.de/context";

    VOSubscription sub = new VOSubscription();
    sub.setServiceInstanceId(instId);
    sub.setOrganizationId(orgId);
    sub.setSubscriptionId(subId);
    sub.setCustomTabUrl(path);

    model.setSelectedSubscription(new POSubscription(sub));

    String urlStr = ctrl.getCustomTabUrlWithParameters();

    assertTrue(urlStr.length() > 0);
    assertTrue(urlStr.contains(Locale.ENGLISH.toLanguageTag()));
    assertTrue(urlStr
            .contains(Base64.encodeBase64URLSafeString(instId.getBytes())));
    assertTrue(urlStr
            .contains(Base64.encodeBase64URLSafeString(orgId.getBytes())));
    assertTrue(urlStr
            .contains(Base64.encodeBase64URLSafeString(subId.getBytes())));

    Files.delete(new File(loc).toPath());
}
 
Example 18
Project: habpanelviewer   File: ConnectionUtil.java   View Source Code Vote up 4 votes
private static void saveTrustStore(KeyStore localTrustStore)
        throws IOException, GeneralSecurityException {
    FileOutputStream out = new FileOutputStream(localTrustStoreFile);
    localTrustStore.store(out, TRUSTSTORE_PASSWORD.toCharArray());
}
 
Example 19
Project: openjdk-jdk10   File: TestKeyStoreEntry.java   View Source Code Vote up 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 20
Project: BiglyBT   File: SESecurityManagerImpl.java   View Source Code Vote up 2 votes
protected SSLSocketFactory
addCertToTrustStore(
	String							alias,
	java.security.cert.Certificate	cert,
	boolean							update_https_factory )

	throws Exception
{
	try{
		this_mon.enter();

		KeyStore keystore = getTrustStore();

		if ( cert != null ){

			if ( keystore.containsAlias( alias )){

				keystore.deleteEntry( alias );
			}

			keystore.setCertificateEntry(alias, cert);

			FileOutputStream	out = null;

			try{
				out = new FileOutputStream(truststore_name);

				keystore.store(out, SESecurityManager.SSL_PASSWORD.toCharArray());

			}finally{

				if ( out != null ){

					out.close();
				}
			}
		}

			// pick up the changed trust store

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

		tmf.init(keystore);

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

		ctx.init(null, tmf.getTrustManagers(), null);

		SSLSocketFactory	factory = ctx.getSocketFactory();

		if ( update_https_factory ){

			HttpsURLConnection.setDefaultSSLSocketFactory( factory );
		}

		return( factory );
	}finally{

		this_mon.exit();
	}
}