Example usage for java.security KeyStore size

List of usage examples for java.security KeyStore size

Introduction

In this page you can find the example usage for java.security KeyStore size.

Prototype

public final int size() throws KeyStoreException 

Source Link

Document

Retrieves the number of entries in this keystore.

Usage

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java

private void init(String args[]) {

    FileInputStream file_inputstream;
    try {/*from w w  w  .  j ava 2s  . com*/
        String pwd = args[ARG_KEYSTOREPASSWORD];
        String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE];
        file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, pwd.toCharArray());
        System.out.println("Keystore size " + keyStore.size());
        Enumeration aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
        Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray());
        getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        innerSignKey = keyFactory.generatePrivate(keySpec);
        innerCertificate = keyStore.getCertificate(certNameInKeystore);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }

    try {
        KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA");
        outerSignKey = outerSignKeys.getPrivate();
        X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null,
                outerSignKeys.getPrivate(), outerSignKeys.getPublic(),
                PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC");

        writeCertificate(signCert, "/opt/racerts", "cmpTest.pem");

        /*
        ArrayList<Certificate> certCollection = new ArrayList<Certificate>();
        certCollection.add(signCert);
        byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection);
                
        FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem"));
        out.write(pemRaCert);
        out.close();
        */
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace();
    } catch (InvalidAlgorithmParameterException e1) {
        e1.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        //} catch (FileNotFoundException e) {
        //   e.printStackTrace();
        //} catch (IOException e) {
        //   e.printStackTrace();
        //} catch (CertificateException e) {
        //   e.printStackTrace();
    }

}

From source file:org.jboss.additional.testsuite.jdkall.present.elytron.application.CredentialStoreTestCase.java

/**
 * Tests credential store with automatically created PKCS12 keystore.
 *//*w  w w .  j a  v  a2 s.  co  m*/
@Test
@Ignore
public void testCredentialStoreCreating() throws Exception {
    String storeName = NAME;
    File tempFolder = Utils.createTemporaryFolder(storeName);
    String fileName = System.currentTimeMillis() + ".p12";
    File ksFile = new File(tempFolder, fileName);
    assertTrue(tempFolder.isDirectory());
    assertFalse(ksFile.exists());
    try {
        try (CLIWrapper cli = new CLIWrapper(true)) {
            cli.sendLine(String.format("/path=%s:add(path=\"%s\")", storeName, asAbsolutePath(tempFolder)));
            SimpleCredentialStore storeConfig = SimpleCredentialStore.builder().withName(storeName)
                    .withKeyStorePath(Path.builder().withPath(fileName).withRelativeTo(storeName).build())
                    .withCredential(CredentialReference.builder().withClearText("pkcs12pass").build())
                    .withKeyStoreType("PKCS12").withModifiable(true).withCreate(true)
                    .withAlias("elytron", "rocks!").build();
            try {
                storeConfig.create(cli);

                assertContainsAliases(cli, storeName, "elytron");

                assertTrue(ksFile.exists());

                cli.sendLine(String.format(
                        "/subsystem=elytron/credential-store=%s:add-alias(alias=another-secret, secret-value=\"%1$s\")",
                        storeName));

                assertCredentialValue(storeName, "elytron", "rocks!");
                assertCredentialValue(storeName, "another-secret", storeName);
            } finally {
                // this should remove alias "elytron" from KeyStore file and remove credential {@value NAME} from domain
                // model
                storeConfig.remove(cli);
            }
            // KeyStore file should not be removed after
            assertTrue(ksFile.exists());
            KeyStore ks = KeyStore.getInstance("PKCS12");
            try (FileInputStream fis = new FileInputStream(ksFile)) {
                ks.load(fis, "pkcs12pass".toCharArray());
                assertEquals(1, ks.size());
                assertTrue(ks.aliases().nextElement().contains("another-secret"));
            }
        }
    } finally {
        FileUtils.deleteQuietly(tempFolder);
    }
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java

@Override
public void generateKey(String keyAlgorithm, String keySpec, String alias, char[] authCode,
        Map<String, Object> params, IServices services)
        throws CryptoTokenOfflineException, IllegalArgumentException {
    if (keySpec == null) {
        throw new IllegalArgumentException("Missing keyspec parameter");
    }/*w  w  w.ja v a  2 s . c  om*/
    if (alias == null) {
        throw new IllegalArgumentException("Missing alias parameter");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("keyAlgorithm: " + keyAlgorithm + ", keySpec: " + keySpec + ", alias: " + alias);
    }
    try {

        final KeyStore keystore = getKeyStore();

        // Check key generation limit, if configured
        if (keygenerationLimit != null && keygenerationLimit > -1) {
            final int current;
            try {
                current = keystore.size();
                if (current >= keygenerationLimit) {
                    throw new TokenOutOfSpaceException("Key generation limit exceeded: " + current);
                }
            } catch (KeyStoreException ex) {
                LOG.error("Checking key generation limit failed", ex);
                throw new TokenOutOfSpaceException(
                        "Current number of key entries could not be obtained: " + ex.getMessage(), ex);
            }
        }

        final KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm, "BC");

        if ("ECDSA".equals(keyAlgorithm)) {
            kpg.initialize(ECNamedCurveTable.getParameterSpec(keySpec));
        } else {
            kpg.initialize(Integer.valueOf(keySpec));
        }

        final String sigAlgName = "SHA1With" + keyAlgorithm;

        LOG.debug("generating...");
        final KeyPair keyPair = kpg.generateKeyPair();
        Certificate[] chain = new Certificate[1];
        chain[0] = CryptoTokenHelper.createDummyCertificate(alias, sigAlgName, keyPair,
                getProvider(PROVIDERUSAGE_SIGN));
        LOG.debug("Creating certificate with entry " + alias + '.');

        keystore.setKeyEntry(alias, keyPair.getPrivate(), authCode, chain);

        final OutputStream os;

        if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
            os = new ByteArrayOutputStream();
        } else {
            os = new FileOutputStream(new File(keystorepath));
        }

        keystore.store(os, authenticationCode);

        if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
            final ByteArrayOutputStream baos = (ByteArrayOutputStream) os;

            final IWorkerSession.ILocal workerSessionLocal = services.get(IWorkerSession.ILocal.class);
            if (workerSessionLocal == null) {
                throw new IllegalStateException("No WorkerSession available");
            }
            workerSessionLocal.setKeystoreData(new AdminInfo("Internal", null, null), workerId,
                    baos.toByteArray());
        }

        final KeyEntry entry = new KeyEntry((PrivateKey) keyPair.getPrivate(), chain[0], Arrays.asList(chain));

        // If this is the first entry
        entries.put(alias, entry);
        if (properties.getProperty(DEFAULTKEY) == null) {
            properties.setProperty(DEFAULTKEY, alias);
            entries.put(ICryptoToken.PURPOSE_SIGN, entry);
            entries.put(ICryptoToken.PURPOSE_DECRYPT, entry);
        }

    } catch (UnsupportedOperationException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (KeyStoreException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (NoSuchProviderException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (InvalidAlgorithmParameterException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (NumberFormatException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (CertificateException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (IOException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    } catch (IllegalStateException ex) {
        LOG.error(ex, ex);
        throw new CryptoTokenOfflineException(ex);
    }
}

From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java

@BeforeClass
public static void setUp() throws Exception {
    mockRetryAfter(); // no need to sleep in between polling attempts during testing
    KeyStore keyStore = KeyStore.getInstance("jks");
    try (InputStream is = AcmeClientSpiTest.class.getResourceAsStream(KEYSTORE)) {
        keyStore.load(is, KEYSTORE_PASSWORD);
    }//from ww w .  j  a va 2  s . co m

    int numAliases = keyStore.size();
    aliasToCertificateMap = new HashMap<>(numAliases);
    aliasToPrivateKeyMap = new HashMap<>(numAliases);
    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        aliasToCertificateMap.put(alias, (X509Certificate) keyStore.getCertificate(alias));
        aliasToPrivateKeyMap.put(alias, (PrivateKey) keyStore.getKey(alias, KEYSTORE_PASSWORD));
    }
    server = new ClientAndServer(4001);
    client = new MockWebServer();
    client.start(5002); // this is the port our mock Let's Encrypt server will use to access the client
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

private String createKeyStoreErrorMessage(KeyStore keystore) throws KeyStoreException {
    Enumeration<String> aliases = keystore.aliases();
    StringBuilder sb = new StringBuilder(keystore.size() * 7);
    boolean firstAlias = true;
    while (aliases.hasMoreElements()) {
        if (!firstAlias) {
            sb.append(", ");
        }//from www.  j  a  va2  s . c  om
        sb.append(aliases.nextElement());
        firstAlias = false;
    }
    String msg = " in keystore of type [" + keystore.getType() + "] from provider [" + keystore.getProvider()
            + "] with size [" + keystore.size() + "] and aliases: {" + sb.toString() + "}";
    return msg;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testBeIDSignature() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    final BeIDCard beIDCard = getBeIDCard();
    keyStoreParameter.setBeIDCard(beIDCard);
    keyStoreParameter.setLogoff(true);/*w  ww  .ja va  2s . c o m*/
    keyStore.load(keyStoreParameter);

    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    assertEquals(2, keyStore.size());

    assertTrue(keyStore.containsAlias("Signature"));
    assertTrue(keyStore.containsAlias("Authentication"));
    assertNotNull(keyStore.getCreationDate("Signature"));
    assertNotNull(keyStore.getCreationDate("Authentication"));

    assertTrue(keyStore.isKeyEntry("Signature"));
    final X509Certificate signCertificate = (X509Certificate) keyStore.getCertificate("Signature");
    assertNotNull(signCertificate);

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);

    assertNotNull(keyStore.getCertificateChain("Signature"));
    assertNotNull(keyStore.getCertificateChain("Authentication"));

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    assertNotNull(authnPrivateKey);

    assertTrue(keyStore.isKeyEntry("Signature"));
    final PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    assertNotNull(signPrivateKey);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", signPrivateKey, signCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());

    Security.addProvider(new BouncyCastleProvider());

    verifySignatureAlgorithm("SHA1withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
}