Search in sources :

Example 86 with Key

use of java.security.Key in project jdk8u_jdk by JetBrains.

the class MetadataEmptyTest method runTest.

private void runTest() throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH, Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks.getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry((PrivateKey) key, new Certificate[] { cert });
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set " + "must be empty");
    }
    out.println("Test Passed");
}
Also used : KeyStore(java.security.KeyStore) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Certificate(java.security.cert.Certificate)

Example 87 with Key

use of java.security.Key in project jdk8u_jdk by JetBrains.

the class MetadataStoreLoadTest method storeAttrs.

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);
}
Also used : PKCS12Attribute(java.security.PKCS12Attribute) KeyStore(java.security.KeyStore) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Certificate(java.security.cert.Certificate) HashSet(java.util.HashSet)

Example 88 with Key

use of java.security.Key in project jdk8u_jdk by JetBrains.

the class WriteP12Test method testTwoEntry.

private void testTwoEntry(String inKeyStoreOnePath, String inKeyStoreTwoPath, String userAlias, String outStorePass, String outKeyPass) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    // initial KeyStore
    KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
    try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
        outputKeyStore.load(null, null);
        KeyStore inputKeyStoreOne, inputKeyStoreTwo;
        inputKeyStoreOne = KeyStore.getInstance(IN_KEYSTORE_TYPE, IN_KEYSTORE_PRV);
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need
        // decode first.
        byte[] inputBytes = Files.readAllBytes(Paths.get(CERT_PATH, inKeyStoreOnePath));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode(inputBytes));
        // input key store
        inputKeyStoreOne.load(arrayIn, IN_STORE_PASS.toCharArray());
        inputBytes = Files.readAllBytes(Paths.get(CERT_PATH, inKeyStoreTwoPath));
        arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode(inputBytes));
        inputKeyStoreTwo = KeyStore.getInstance(IN_KEYSTORE_TYPE, IN_KEYSTORE_PRV);
        inputKeyStoreTwo.load(arrayIn, IN_STORE_PASS.toCharArray());
        // add key/certificate to output key store
        out.println("====First Entry=====");
        Key inputKey = inputKeyStoreOne.getKey(userAlias, IN_KEY_PASS.toCharArray());
        Certificate cert = inputKeyStoreOne.getCertificate(userAlias);
        Certificate[] certs = new Certificate[1];
        certs[0] = cert;
        out.println("====Input1 Key=====");
        out.println(inputKey.getAlgorithm());
        out.println("====Input1 Certs=====");
        out.println("Certificate :");
        out.println(((X509Certificate) cert).getSubjectDN());
        outputKeyStore.setKeyEntry("USER", inputKey, outKeyPass.toCharArray(), certs);
        out.println("====Second Entry=====");
        String caAlias = "pkcs12testca";
        inputKey = inputKeyStoreTwo.getKey(caAlias, IN_KEY_PASS.toCharArray());
        cert = inputKeyStoreTwo.getCertificate(caAlias);
        certs[0] = cert;
        out.println("====Input2 Key=====");
        out.println(inputKey.getAlgorithm());
        out.println("====Input2 Certs=====");
        out.println("Certificate :");
        out.println(((X509Certificate) cert).getSubjectDN());
        outputKeyStore.setKeyEntry("CA", inputKey, outKeyPass.toCharArray(), certs);
        // save output
        outputKeyStore.store(fout, outStorePass.toCharArray());
        // test output
        testKeyStore(outputKeyStore, outKeyPass.toCharArray());
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) KeyStore(java.security.KeyStore) Key(java.security.Key) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 89 with Key

use of java.security.Key in project jdk8u_jdk by JetBrains.

the class ReadP12Test method readTest.

private void readTest(String inKeyStore) throws Exception {
    KeyStore inputKeyStore;
    // Initialize KeyStore
    String dir = System.getProperty("test.src", ".");
    String keystorePath = dir + File.separator + "certs" + File.separator + "readP12";
    inputKeyStore = KeyStore.getInstance(IN_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
    // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
    // first.
    byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
    ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode(input));
    inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
    out.println("Initialize KeyStore : " + inKeyStore + " success");
    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());
    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
        alias = e.nextElement();
        out.println("Alias " + idx + " : " + alias);
        if (inputKeyStore.containsAlias(alias) == false) {
            throw new RuntimeException("Alias not found");
        }
        out.println("getCreationDate : " + inputKeyStore.getCreationDate(alias));
        X509Certificate cert = (X509Certificate) inputKeyStore.getCertificate(alias);
        out.println("getCertificate : " + cert.getSubjectDN());
        String retAlias = inputKeyStore.getCertificateAlias(cert);
        if (!retAlias.equals(alias)) {
            throw new RuntimeException("Alias mismatch");
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        for (int i = 0; i < certs.length; i++) {
            out.println("getCertificateChain " + i + " : " + ((X509Certificate) certs[i]).getSubjectDN());
        }
        boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
        // test KeyStore only contain key pair entries.
        if (isCertEntry == true) {
            throw new RuntimeException("inputKeystore should not be certEntry because test keystore only contain key pair entries.");
        }
        boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
        if (isKeyEntry) {
            Key key = inputKeyStore.getKey(alias, IN_STORE_PASS.toCharArray());
            out.println("Key : " + key.toString());
        } else {
            throw new RuntimeException("Entry type unknown\n");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match");
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 90 with Key

use of java.security.Key in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreTest method testKeyStore_GetKey_NoPassword_Encrypted_Success.

public void testKeyStore_GetKey_NoPassword_Encrypted_Success() throws Exception {
    setupPassword();
    mKeyStore.load(null, null);
    assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1, FAKE_RSA_KEY_1, KeyStore.UID_SELF, KeyStore.FLAG_ENCRYPTED));
    assertTrue(mAndroidKeyStore.put(Credentials.USER_CERTIFICATE + TEST_ALIAS_1, FAKE_RSA_USER_1, KeyStore.UID_SELF, KeyStore.FLAG_ENCRYPTED));
    assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_RSA_CA_1, KeyStore.UID_SELF, KeyStore.FLAG_ENCRYPTED));
    Key key = mKeyStore.getKey(TEST_ALIAS_1, null);
    assertNotNull("Key should exist", key);
    assertTrue("Should be a PrivateKey", key instanceof PrivateKey);
    assertTrue("Should be a RSAKey", key instanceof RSAKey);
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_RSA_KEY_1));
    assertEquals("Inserted key should be same as retrieved key", ((RSAKey) expectedKey).getModulus(), ((RSAKey) key).getModulus());
}
Also used : RSAKey(java.security.interfaces.RSAKey) PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) RSAKey(java.security.interfaces.RSAKey) ECKey(java.security.interfaces.ECKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) KeyFactory(java.security.KeyFactory)

Aggregations

Key (java.security.Key)302 PrivateKey (java.security.PrivateKey)112 SecretKey (javax.crypto.SecretKey)83 KeyStore (java.security.KeyStore)64 PublicKey (java.security.PublicKey)62 Cipher (javax.crypto.Cipher)60 X509Certificate (java.security.cert.X509Certificate)57 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)50 Test (org.junit.Test)44 IOException (java.io.IOException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 SecretKeySpec (javax.crypto.spec.SecretKeySpec)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)32 KeyGenerator (javax.crypto.KeyGenerator)32 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 KeyStoreException (java.security.KeyStoreException)22 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21