List of usage examples for java.security KeyStoreException getMessage
public String getMessage()
From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java
@Override public int importKeyStore(final KeyStore keyStore, final MissingKey missingKey) throws KeyStoreException { Check.notNull(keyStore, "keyStore"); Check.notNull(missingKey, "missingKey"); int importedEntries = 0; try {// w ww . j ava 2 s. c o m importedEntries = getActionExecutor().executeTransaction(new DatabaseAction<Integer>() { @Override public Integer doAction(Session session) throws DatabaseException { try { Session previousSession = getSessionManager().getSession(); getSessionManager().setSession(session); try { return importKeyStoreTransacted(keyStore, missingKey); } finally { /* restore the session */ getSessionManager().setSession(previousSession); } } catch (KeyStoreException e) { throw new DatabaseException(e); } } }); } catch (DatabaseException e) { Throwable cause = e.getCause(); if (cause == null) { cause = e; } if (cause instanceof KeyStoreException) { throw (KeyStoreException) cause; } throw new KeyStoreException(cause); } catch (ConstraintViolationException e) { logger.warn( "ConstraintViolationException. A certificate was probably already in the certStore. Message: " + e.getMessage()); } return importedEntries; }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
/** * addCACertificateToTrustStore adds a CA cert to the set of certificates used for signature validation * * @param caCert an X.509 certificate//from www . j a v a2 s . co m * @param alias an alias associated with the certificate. Used as shorthand for the certificate during crypto operations * @throws CryptoException * @throws InvalidArgumentException */ void addCACertificateToTrustStore(Certificate caCert, String alias) throws InvalidArgumentException, CryptoException { if (alias == null || alias.isEmpty()) { throw new InvalidArgumentException( "You must assign an alias to a certificate when adding to the trust store."); } if (caCert == null) { throw new InvalidArgumentException("Certificate cannot be null."); } try { if (config.extraLogLevel(10)) { if (null != diagnosticFileDumper) { logger.trace(format("Adding cert to trust store. alias: %s. certificate:", alias) + diagnosticFileDumper.createDiagnosticFile(alias + "cert: " + caCert.toString())); } } synchronized (certificateSet) { if (certificateSet.contains(alias)) { return; } getTrustStore().setCertificateEntry(alias, caCert); certificateSet.add(alias); } } catch (KeyStoreException e) { String emsg = "Unable to add CA certificate to trust store. Error: " + e.getMessage(); logger.error(emsg, e); throw new CryptoException(emsg, e); } }
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 va 2s .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.wisdom.engine.ssl.SSLServerContext.java
/** * Constructor for singleton.//w w w .j av a 2 s . c o m * * @param accessor used to access services. */ private SSLServerContext(final ServiceAccessor accessor) { LOGGER.info("Configuring HTTPS support"); this.accessor = accessor; final File root = accessor.getConfiguration().getBaseDir(); final String path = accessor.getConfiguration().get("https.keyStore"); final String ca = accessor.getConfiguration().get("https.trustStore"); KeyManagerFactory kmf = null; TrustManager[] trusts = null; // configure keystore if (path == null) { kmf = getFakeKeyManagerFactory(root); LOGGER.warn(HTTPSWARN); trusts = new TrustManager[] { new AcceptAllTrustManager() }; } else { try { kmf = getKeyManagerFactoryFromKeyStore(root, path); } catch (final KeyStoreException e) { throw new RuntimeException("Cannot read the key store file", e); } } // configure trustore if (ca == null) { LOGGER.info("Using default trust store for client side CA verification"); } else if ("noCA".equalsIgnoreCase(ca)) { trusts = new TrustManager[] { new AcceptAllTrustManager() }; LOGGER.warn(HTTPSWARN); } else { try { trusts = getTrustManagerFactoryFromKeyStore(root, ca).getTrustManagers(); } catch (final KeyStoreException e) { throw new RuntimeException("Cannot read the trust store file", e); } } try { final SSLContext context = SSLContext.getInstance(PROTOCOL); context.init(kmf.getKeyManagers(), trusts, null); serverContext = context; } catch (final Exception e) { throw new RuntimeException(HTTPSFAIL + e.getMessage(), e); } }
From source file:ca.uhn.hl7v2.testpanel.model.conn.AbstractConnection.java
protected LowerLayerProtocol createLlp() throws LLPException { LowerLayerProtocol llpClass;/*from ww w . ja va 2 s. c om*/ if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP) { ServerRoleEnum role = isInbound() ? ServerRoleEnum.SERVER : ServerRoleEnum.CLIENT; Hl7OverHttpLowerLayerProtocol hohLlp = new Hl7OverHttpLowerLayerProtocol(role); if (isHohAuthenticationEnabled()) { if (isInbound()) { hohLlp.setAuthorizationCallback(new SingleCredentialServerCallback( getHohAuthenticationUsername(), getHohAuthenticationPassword())); } else { hohLlp.setAuthorizationCallback(new SingleCredentialClientCallback( getHohAuthenticationUsername(), getHohAuthenticationPassword())); } } if (isHohSignatureEnabled()) { BouncyCastleCmsMessageSigner signer = new BouncyCastleCmsMessageSigner(); try { signer.setKeyStore(getHohSignatureKeystore_()); } catch (KeyStoreException e) { throw new LLPException(e.getMessage(), e); } signer.setKeyAlias(getHohSignatureKey()); signer.setAliasPassword(getHohSignatureKeyPassword()); hohLlp.setSigner(signer); } hohLlp.setUriPath(getHttpUriPath()); llpClass = hohLlp; } else if (isDetectCharSetInMessage()) { llpClass = new ExtendedMinLowerLayerProtocol(); } else { MinLowerLayerProtocol llp = new MinLowerLayerProtocol(); llp.setCharset(Charset.forName(getCharSet())); llpClass = llp; } if (isCaptureBytes()) { llpClass = new ByteCapturingMinLowerLayerProtocolWrapper(llpClass, myReaderCapture, myWriterCapture); } return llpClass; }
From source file:ca.uhn.hl7v2.testpanel.model.conn.AbstractConnection.java
SocketFactory getSocketFactory() { return new SocketFactory() { @Override// w w w . j a va2s. c o m public Socket createTlsSocket() throws IOException { try { if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP && getTlsKeystore() != null) { return createHohSocketFactory().createClientSocket(); } } catch (KeyStoreException e) { throw new IOException(e.getMessage(), e); } return SSLSocketFactory.getDefault().createSocket(); } @Override public ServerSocket createTlsServerSocket() throws IOException { try { if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP && getHohSignatureKeystore_() != null) { return createHohSocketFactory().createServerSocket(); } } catch (KeyStoreException e) { throw new IOException(e.getMessage(), e); } return SSLServerSocketFactory.getDefault().createServerSocket(); } private CustomCertificateTlsSocketFactory createHohSocketFactory() throws KeyStoreException { KeyStore keystore = getTlsKeystore(); String keystorePassword = getTlsKeystorePassword(); CustomCertificateTlsSocketFactory sf = new CustomCertificateTlsSocketFactory(keystore, keystorePassword); return sf; } @Override public Socket createSocket() throws IOException { return javax.net.SocketFactory.getDefault().createSocket(); } @Override public ServerSocket createServerSocket() throws IOException { return ServerSocketFactory.getDefault().createServerSocket(); } @Override public void configureNewAcceptedSocket(Socket theSocket) throws SocketException { // nothing } }; }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Gets the private key corresponding to the identifier. * * @param identifier The implementation-specific identifier corresponding to the key * @param password The password needed to get the key * @return The private key//from w w w . j a va2 s . com */ public PrivateKey getPrivateKey(String identifier, String password) throws WSSecurityException { if (keystore == null) { throw new WSSecurityException("The keystore is null"); } try { if (identifier == null || !keystore.isKeyEntry(identifier)) { String msg = "Cannot find key for alias: [" + identifier + "]"; String logMsg = createKeyStoreErrorMessage(keystore); LOG.error(msg + logMsg); throw new WSSecurityException(msg); } if (password == null && privatePasswordSet) { password = properties.getProperty(KEYSTORE_PRIVATE_PASSWORD); if (password != null) { password = password.trim(); } } Key keyTmp = keystore.getKey(identifier, password == null ? new char[] {} : password.toCharArray()); if (!(keyTmp instanceof PrivateKey)) { String msg = "Key is not a private key, alias: [" + identifier + "]"; String logMsg = createKeyStoreErrorMessage(keystore); LOG.error(msg + logMsg); throw new WSSecurityException(msg); } return (PrivateKey) keyTmp; } catch (KeyStoreException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPrivateKey", new Object[] { ex.getMessage() }, ex); } catch (UnrecoverableKeyException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPrivateKey", new Object[] { ex.getMessage() }, ex); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPrivateKey", new Object[] { ex.getMessage() }, ex); } }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Gets the private key corresponding to the certificate. * * @param certificate The X509Certificate corresponding to the private key * @param callbackHandler The callbackHandler needed to get the password * @return The private key/*from ww w.ja v a2 s.c o m*/ */ public PrivateKey getPrivateKey(X509Certificate certificate, CallbackHandler callbackHandler) throws WSSecurityException { if (keystore == null) { throw new WSSecurityException("The keystore is null"); } if (callbackHandler == null) { throw new WSSecurityException("The CallbackHandler is null"); } String identifier = getIdentifier(certificate, keystore); try { if (identifier == null || !keystore.isKeyEntry(identifier)) { String msg = "Cannot find key for alias: [" + identifier + "]"; String logMsg = createKeyStoreErrorMessage(keystore); LOG.error(msg + logMsg); throw new WSSecurityException(msg); } String password = getPassword(identifier, callbackHandler); if (password == null && privatePasswordSet) { password = properties.getProperty(KEYSTORE_PRIVATE_PASSWORD); if (password != null) { password = password.trim(); } } Key keyTmp = keystore.getKey(identifier, password == null ? new char[] {} : password.toCharArray()); if (!(keyTmp instanceof PrivateKey)) { String msg = "Key is not a private key, alias: [" + identifier + "]"; String logMsg = createKeyStoreErrorMessage(keystore); LOG.error(msg + logMsg); throw new WSSecurityException(msg); } return (PrivateKey) keyTmp; } catch (KeyStoreException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPrivateKey", new Object[] { ex.getMessage() }, ex); } catch (UnrecoverableKeyException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPrivateKey", new Object[] { ex.getMessage() }, ex); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPrivateKey", new Object[] { ex.getMessage() }, ex); } }
From source file:net.jsign.PESignerCLI.java
void execute(String... args) throws SignerException { DefaultParser parser = new DefaultParser(); try {/*from w ww .ja va 2s. co m*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help") || args.length == 0) { printHelp(); return; } File keystore = cmd.hasOption("keystore") ? new File(cmd.getOptionValue("keystore")) : null; String storepass = cmd.getOptionValue("storepass"); String storetype = cmd.getOptionValue("storetype"); String alias = cmd.getOptionValue("alias"); String keypass = cmd.getOptionValue("keypass"); File keyfile = cmd.hasOption("keyfile") ? new File(cmd.getOptionValue("keyfile")) : null; File certfile = cmd.hasOption("certfile") ? new File(cmd.getOptionValue("certfile")) : null; String tsaurl = cmd.getOptionValue("tsaurl"); String tsmode = cmd.getOptionValue("tsmode"); String algorithm = cmd.getOptionValue("alg"); String name = cmd.getOptionValue("name"); String url = cmd.getOptionValue("url"); File file = cmd.getArgList().isEmpty() ? null : new File(cmd.getArgList().get(0)); if (keystore != null && storetype == null) { // guess the type of the keystore from the extension of the file String filename = keystore.getName().toLowerCase(); if (filename.endsWith(".p12") || filename.endsWith(".pfx")) { storetype = "PKCS12"; } else { storetype = "JKS"; } } PrivateKey privateKey; Certificate[] chain; // some exciting parameter validation... if (keystore == null && keyfile == null && certfile == null) { throw new SignerException("keystore option, or keyfile and certfile options must be set"); } if (keystore != null && (keyfile != null || certfile != null)) { throw new SignerException("keystore option can't be mixed with keyfile or certfile"); } if (keystore != null) { // JKS or PKCS12 keystore KeyStore ks; try { ks = KeyStore.getInstance(storetype); } catch (KeyStoreException e) { throw new SignerException("keystore type '" + storetype + "' is not supported", e); } if (!keystore.exists()) { throw new SignerException("The keystore " + keystore + " couldn't be found"); } FileInputStream in = null; try { in = new FileInputStream(keystore); ks.load(in, storepass != null ? storepass.toCharArray() : null); } catch (Exception e) { throw new SignerException("Unable to load the keystore " + keystore, e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { // ignore } } if (alias == null) { throw new SignerException("alias option must be set"); } try { chain = ks.getCertificateChain(alias); } catch (KeyStoreException e) { throw new SignerException(e.getMessage(), e); } if (chain == null) { throw new SignerException( "No certificate found under the alias '" + alias + "' in the keystore " + keystore); } char[] password = keypass != null ? keypass.toCharArray() : storepass.toCharArray(); try { privateKey = (PrivateKey) ks.getKey(alias, password); } catch (Exception e) { throw new SignerException("Failed to retrieve the private key from the keystore", e); } } else { // separate private key and certificate files (PVK/SPC) if (keyfile == null) { throw new SignerException("keyfile option must be set"); } if (!keyfile.exists()) { throw new SignerException("The keyfile " + keyfile + " couldn't be found"); } if (certfile == null) { throw new SignerException("certfile option must be set"); } if (!certfile.exists()) { throw new SignerException("The certfile " + certfile + " couldn't be found"); } // load the certificate chain try { chain = loadCertificateChain(certfile); } catch (Exception e) { throw new SignerException("Failed to load the certificate from " + certfile, e); } // load the private key try { privateKey = PVK.parse(keyfile, keypass); } catch (Exception e) { throw new SignerException("Failed to load the private key from " + keyfile, e); } } if (algorithm != null && DigestAlgorithm.of(algorithm) == null) { throw new SignerException("The digest algorithm " + algorithm + " is not supported"); } if (file == null) { throw new SignerException("missing file argument"); } if (!file.exists()) { throw new SignerException("The file " + file + " couldn't be found"); } PEFile peFile; try { peFile = new PEFile(file); } catch (IOException e) { throw new SignerException("Couldn't open the executable file " + file, e); } // and now the actual work! PESigner signer = new PESigner(chain, privateKey).withProgramName(name).withProgramURL(url) .withDigestAlgorithm(DigestAlgorithm.of(algorithm)) .withTimestamping(tsaurl != null || tsmode != null) .withTimestampingMode(TimestampingMode.of(tsmode)).withTimestampingAutority(tsaurl); try { System.out.println("Adding Authenticode signature to " + file); signer.sign(peFile); } catch (Exception e) { throw new SignerException("Couldn't sign " + file, e); } finally { try { peFile.close(); } catch (IOException e) { System.err.println("Couldn't close " + file); e.printStackTrace(System.err); } } } catch (ParseException e) { e.printStackTrace(); } }
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * /*from w w w.jav a 2 s . c o m*/ * @param keyInfo the key info * @param ownKeyStore * @param ownKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) { LOG.trace("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA); final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(HEXA); X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (CertificateException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (RuntimeException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } return alias; }