List of usage examples for java.security KeyStore isKeyEntry
public final boolean isKeyEntry(String alias) throws KeyStoreException
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#loadPKCS12Keystore(java.io.File, java.lang.String)}. * @throws CMException //from ww w . ja va 2 s .c o m * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException */ @Test public void testLoadPKCS12Keystore() throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(new File(privateKeyFileURL.getPath()), privateKeyAndPKCS12KeystorePassword); Key privateKey2 = null; Certificate[] privateKeyCertChain2 = null; Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey2 = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain2 = pkcs12Keystore.getCertificateChain(alias); break; } } assertNotNull(privateKey2); assertNotNull(privateKeyCertChain2); }
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);/*from ww w . j av a2 s . c om*/ 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()); }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#loadPKCS12Keystore(java.io.File, java.lang.String)}. * @throws CMException /*from w ww. ja va 2 s . c o m*/ * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException */ @Test public void testLoadPKCS12Keystore() throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore( new File(privateKeyFileURL.getPath()).toPath(), privateKeyAndPKCS12KeystorePassword); Key privateKey2 = null; Certificate[] privateKeyCertChain2 = null; Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey2 = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain2 = pkcs12Keystore.getCertificateChain(alias); break; } } assertNotNull(privateKey2); assertNotNull(privateKeyCertChain2); }
From source file:org.eclipse.gyrex.admin.ui.http.jetty.internal.ImportCertificateDialog.java
void importKeystore(final InputStream in) throws Exception { KeyStore tempKs; if (keystoreTypeField.isSelected(0)) { tempKs = KeyStore.getInstance("JKS"); } else if (keystoreTypeField.isSelected(1)) { tempKs = KeyStore.getInstance("PKCS12"); } else {// w w w.j a v a 2s .com throw new IllegalArgumentException( "Please select a keystore type before uploading a keystore and retry."); } final String keystorePassword = keyStorePasswordField.getText(); final String keyPassword = keyPasswordField.getText(); // load keystore tempKs.load(new BufferedInputStream(in), null != keystorePassword ? keystorePassword.toCharArray() : null); // initialize new JKS store final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); generatedKeystorePassword = UUID.randomUUID().toString().toCharArray(); generatedKeyPassword = UUID.randomUUID().toString().toCharArray(); // verify and copy into new store final Enumeration aliases = tempKs.aliases(); while (aliases.hasMoreElements()) { final String alias = (String) aliases.nextElement(); if (tempKs.isKeyEntry(alias)) { final Key key = tempKs.getKey(alias, null != keyPassword ? keyPassword.toCharArray() : null != keystorePassword ? keystorePassword.toCharArray() : null); Certificate[] chain = tempKs.getCertificateChain(alias); if (null == chain) { final Certificate certificate = tempKs.getCertificate(alias); if (null == certificate) { // skip to next continue; } chain = new Certificate[] { certificate }; } ks.setKeyEntry("jetty", key, generatedKeyPassword, chain); break; } } if (!ks.aliases().hasMoreElements()) { throw new IllegalArgumentException( "The uploaded keystore does not have a valid key + certificate chain entry. Please use a different keystore and retry."); } // write into bytes final ByteArrayOutputStream out = new ByteArrayOutputStream(); ks.store(out, generatedKeystorePassword); keystoreBytes = out.toByteArray(); }
From source file:it.cnr.icar.eric.common.security.KeystoreMover.java
public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword, String sourceAlias, String sourceKeyPassword, String destinationKeystoreType, String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias, String destinationKeyPassword) throws Exception { char[] sourceKeystorePasswordArr = null; if (sourceKeystorePassword != null) { sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray(); }/*from ww w. ja v a 2 s .c o m*/ char[] sourceKeyPasswordArr = sourceKeystorePasswordArr; if (sourceKeyPassword != null) { sourceKeyPasswordArr = sourceKeyPassword.toCharArray(); } char[] destinationKeystorePasswordArr = null; if (destinationKeystorePassword != null) { destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray(); } char[] destinationKeyPasswordArr = destinationKeystorePasswordArr; if (destinationKeyPassword != null) { destinationKeyPasswordArr = destinationKeyPassword.toCharArray(); } FileInputStream in; // -------- Load source keystore to memory --------- in = new FileInputStream(sourceKeystorePath); KeyStore ksin = KeyStore.getInstance(sourceKeystoreType); ksin.load(in, sourceKeystorePasswordArr); in.close(); // -------- Load destination keystore initial contents to memory --------- KeyStore ksout = KeyStore.getInstance(destinationKeystoreType); try { in = new FileInputStream(destinationKeystorePath); ksout.load(in, destinationKeystorePasswordArr); } catch (java.io.FileNotFoundException e) { ksout.load(null, destinationKeystorePasswordArr); } finally { in.close(); } Enumeration<String> en = ksin.aliases(); while (en.hasMoreElements()) { String alias = en.nextElement(); if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) { if (ksout.containsAlias(alias)) { log.info(CommonResourceBundle.getInstance().getString( "message.destinationKeystorePathAlreadyContains", new Object[] { destinationKeystorePath, alias })); continue; } //Use existing alias if no destinationAlias specified if (destinationAlias == null) { destinationAlias = alias; } if (ksin.isCertificateEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate", new Object[] { alias })); ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias)); } if (ksin.isKeyEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingKey", new Object[] { alias })); Certificate[] certChain = ksin.getCertificateChain(alias); ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr), destinationKeyPasswordArr, certChain); } } } //--------- Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores-------------- FileOutputStream out = new FileOutputStream(destinationKeystorePath); ksout.store(out, destinationKeystorePasswordArr); out.close(); log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful")); }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** Creates a PKCS#12 KeyStore with keys only from an JKS file (no issuer certs or trusted certs) */ @Deprecated //Remove this method as soon as upgrading from 5->6 is dropped private KeyStore makeKeysOnlyP12(KeyStore keyStore, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException { final KeyStore p12 = KeyStore.getInstance("PKCS12", "BC"); final KeyStore.ProtectionParameter protParam = (password != null ? new KeyStore.PasswordProtection(password) : null);//from w w w .ja va 2 s.c om p12.load(null, password); // initialize final Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { final String alias = en.nextElement(); if (!keyStore.isKeyEntry(alias)) continue; try { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, protParam); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), password, chain); } catch (UnsupportedOperationException uoe) { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), null, chain); } } return p12; }
From source file:org.lockss.protocol.BlockingStreamComm.java
private void logKeyStore(KeyStore ks, char[] privateKeyPassWord) { log.debug3("start of key store"); try {/*from w w w . j av a 2 s . c om*/ for (Enumeration en = ks.aliases(); en.hasMoreElements();) { String alias = (String) en.nextElement(); log.debug3("Next alias " + alias); if (ks.isCertificateEntry(alias)) { log.debug3("About to Certificate"); java.security.cert.Certificate cert = ks.getCertificate(alias); if (cert == null) { log.debug3(alias + " null cert chain"); } else { log.debug3("Cert for " + alias + " is " + cert.toString()); } } else if (ks.isKeyEntry(alias)) { log.debug3("About to getKey"); Key privateKey = ks.getKey(alias, privateKeyPassWord); log.debug3(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat()); } else { log.debug3(alias + " neither key nor cert"); } } log.debug3("end of key store"); } catch (Exception ex) { log.error("logKeyStore() threw " + ex); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void importCAFromKeyStore(AuthenticationToken admin, String caname, byte[] p12file, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { try {//from w ww . jav a 2 s . co m // check authorization if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", caname); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, details); } // load keystore java.security.KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(new java.io.ByteArrayInputStream(p12file), keystorepass.toCharArray()); // Extract signature keys if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found."); } Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); if (signatureCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; log.error(msg); throw new Exception(msg); } Certificate caSignatureCertificate = (Certificate) signatureCertChain[0]; PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); PrivateKey p12PrivateSignatureKey = null; p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias, privkeypass.toCharArray()); log.debug("ImportSignatureKeyAlgorithm=" + p12PrivateSignatureKey.getAlgorithm()); // Extract encryption keys PrivateKey p12PrivateEncryptionKey = null; PublicKey p12PublicEncryptionKey = null; Certificate caEncryptionCertificate = null; if (privateEncryptionKeyAlias != null) { if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found."); } Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); if (encryptionCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; log.error(msg); throw new Exception(msg); } caEncryptionCertificate = (Certificate) encryptionCertChain[0]; p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias, privkeypass.toCharArray()); p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); } importCAFromKeys(admin, caname, keystorepass, signatureCertChain, p12PublicSignatureKey, p12PrivateSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey); } catch (Exception e) { String detailsMsg = intres.getLocalizedMessage("caadmin.errorimportca", caname, "PKCS12", e.getMessage()); auditSession.log(EjbcaEventTypes.CA_IMPORT, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, detailsMsg); throw new EJBException(e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void restoreCAKeyStore(AuthenticationToken authenticationToken, String caname, byte[] p12file, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { if (log.isTraceEnabled()) { log.trace(">restoreCAKeyStore"); }//from w w w . j a va2 s. com try { // check authorization if (!accessSession.isAuthorizedNoLogging(authenticationToken, StandardRules.ROLE_ROOT.resource())) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorestorecatoken", caname); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); } CA thisCa = caSession.getCAForEdit(authenticationToken, caname); final CAToken thisCAToken = thisCa.getCAToken(); CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (cryptoToken != null) { throw new Exception("CA already has an existing CryptoToken reference: " + cryptoToken.getId()); } // load keystore from input KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray()); // Extract signature keys if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found."); } Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); if (signatureCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; log.error(msg); throw new Exception(msg); } Certificate caSignatureCertificate = (Certificate) signatureCertChain[0]; PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); PrivateKey p12PrivateSignatureKey = null; p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias, privkeypass.toCharArray()); // Extract encryption keys PrivateKey p12PrivateEncryptionKey = null; PublicKey p12PublicEncryptionKey = null; Certificate caEncryptionCertificate = null; if (privateEncryptionKeyAlias != null) { if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found."); } Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); if (encryptionCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; log.error(msg); throw new Exception(msg); } caEncryptionCertificate = (Certificate) encryptionCertChain[0]; p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias, privkeypass.toCharArray()); p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); } else { throw new Exception("Missing encryption key"); } // Sign something to see that we are restoring the right private signature key String testSigAlg = (String) AlgorithmTools .getSignatureAlgorithms(thisCa.getCACertificate().getPublicKey()).iterator().next(); if (testSigAlg == null) { testSigAlg = "SHA1WithRSA"; } // Sign with imported private key byte[] input = "Test data...".getBytes(); Signature signature = Signature.getInstance(testSigAlg, "BC"); signature.initSign(p12PrivateSignatureKey); signature.update(input); byte[] signed = signature.sign(); // Verify with public key from CA certificate signature = Signature.getInstance(testSigAlg, "BC"); signature.initVerify(thisCa.getCACertificate().getPublicKey()); signature.update(input); if (!signature.verify(signed)) { throw new Exception("Could not use private key for verification. Wrong p12-file for this CA?"); } // Import the keys and save to database CAToken catoken = importKeysToCAToken(authenticationToken, keystorepass, thisCAToken.getProperties(), p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey, signatureCertChain, thisCa.getCAId()); thisCa.setCAToken(catoken); // Finally save the CA caSession.editCA(authenticationToken, thisCa, true); // Log final String detailsMsg = intres.getLocalizedMessage("caadmin.restoredcakeystore", Integer.valueOf(thisCa.getCAId())); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(thisCa.getCAId()), null, null, detailsMsg); } catch (Exception e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrestorecakeystore", caname, "PKCS12", e.getMessage()); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); throw new EJBException(e); } if (log.isTraceEnabled()) { log.trace("<restoreCAKeyStore"); } }