List of usage examples for java.security.cert CertificateFactory getInstance
public static final CertificateFactory getInstance(String type) throws CertificateException
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
boolean validateCertificate(Certificate cert) { boolean isValidated; if (cert == null) { return false; }/*from w w w .j ava 2 s . c om*/ try { KeyStore keyStore = getTrustStore(); PKIXParameters parms = new PKIXParameters(keyStore); parms.setRevocationEnabled(false); CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX ArrayList<Certificate> start = new ArrayList<>(); start.add(cert); CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT); CertPath certPath = certFactory.generateCertPath(start); certValidator.validate(certPath, parms); isValidated = true; } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | CertificateException | CertPathValidatorException | CryptoException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + cert.toString()); isValidated = false; } return isValidated; }
From source file:org.globus.gsi.util.CertificateUtil.java
public static CertPath getCertPath(X509Certificate[] certs) throws CertificateException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); return factory.generateCertPath(Arrays.asList(certs)); }
From source file:com.vmware.identity.idm.server.ServerUtils.java
private static X509Certificate getCert(LdapValue value) { X509Certificate cert = null;//from w ww . j a v a2 s .c o m if (value != null) { byte[] certBytes = value.getValue(); if (certBytes != null) { try { ByteArrayInputStream inpstream = new ByteArrayInputStream(certBytes); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inpstream); } catch (CertificateException e) { throw new RuntimeException("Failed to generate certificate"); } } } return cert; }
From source file:com.cloud.bridge.service.EC2RestServlet.java
/** * The SOAP API for EC2 uses WS-Security to sign all client requests. This requires that * the client have a public/private key pair and the public key defined by a X509 certificate. * Thus in order for a Cloud.com account holder to use the EC2's SOAP API he must register * his X509 certificate with the EC2 service. This function allows the Cloud.com account * holder to "load" his X509 certificate into the service. Note, that the SetUserKeys REST * function must be called before this call. * /*from w ww . j ava 2s .c om*/ * This is an authenticated REST call and as such must contain all the required REST parameters * including: Signature, Timestamp, Expires, etc. The signature is calculated using the * Cloud.com account holder's API access and secret keys and the Amazon defined EC2 signature * algorithm. * * A user can call this REST function any number of times, on each call the X509 certificate * simply over writes any previously stored value. */ private void setCertificate(HttpServletRequest request, HttpServletResponse response) throws Exception { Transaction txn = null; try { // [A] Pull the cert and cloud AccessKey from the request String[] certificate = request.getParameterValues("cert"); if (null == certificate || 0 == certificate.length) { response.sendError(530, "Missing cert parameter"); return; } // logger.debug( "SetCertificate cert: [" + certificate[0] + "]" ); String[] accessKey = request.getParameterValues("AWSAccessKeyId"); if (null == accessKey || 0 == accessKey.length) { response.sendError(530, "Missing AWSAccessKeyId parameter"); return; } // [B] Open our keystore FileInputStream fsIn = new FileInputStream(pathToKeystore); KeyStore certStore = KeyStore.getInstance("JKS"); certStore.load(fsIn, keystorePassword.toCharArray()); // -> use the Cloud API key to save the cert in the keystore // -> write the cert into the keystore on disk Certificate userCert = null; CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bs = new ByteArrayInputStream(certificate[0].getBytes()); while (bs.available() > 0) userCert = cf.generateCertificate(bs); certStore.setCertificateEntry(accessKey[0], userCert); FileOutputStream fsOut = new FileOutputStream(pathToKeystore); certStore.store(fsOut, keystorePassword.toCharArray()); // [C] Associate the cert's uniqueId with the Cloud API keys String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert); logger.debug("SetCertificate, uniqueId: " + uniqueId); /* UserCredentialsDao credentialDao = new UserCredentialsDao(); credentialDao.setCertificateId( accessKey[0], uniqueId ); */ txn = Transaction.open(Transaction.AWSAPI_DB); UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); user.setCertUniqueId(uniqueId); ucDao.update(user.getId(), user); response.setStatus(200); endResponse(response, "User certificate set successfully"); txn.commit(); } catch (NoSuchObjectException e) { logger.error("SetCertificate exception " + e.getMessage(), e); response.sendError(404, "SetCertificate exception " + e.getMessage()); } catch (Exception e) { logger.error("SetCertificate exception " + e.getMessage(), e); response.sendError(500, "SetCertificate exception " + e.getMessage()); } finally { txn.close(); } }
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
/** * This function drives the accepting side of the context establishment * process. It is expected to be called in tandem with the * {@link #initSecContext(byte[], int, int) initSecContext} function. * <BR>// w w w . j av a 2 s. c o m * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * and {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} context options. If the * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.MODE_GSI} * credential delegation during context establishment process will be accepted. * If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, a peer * presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data) */ public byte[] acceptSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter acceptSecContext"); if (!this.conn) { this.role = ACCEPT; logger.debug("enter initializing in acceptSecContext"); if (this.ctxCred.getName().isAnonymous()) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "acceptCtx00"); } if (this.ctxCred.getUsage() != GSSCredential.ACCEPT_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } setCredential(); try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in acceptSecContext"); } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("acceptSecContext handshake finished"); handshakeFinished(); // acceptor for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.targetName = this.ctxCred.getName(); // initiator - peer /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { this.sourceName = new GlobusGSSName(); this.anonymity = true; } else { /*DEL X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); String identity = verifyChain(chain); */ for (X509Certificate cert : (X509Certificate[]) chain) { setGoodUntil(cert.getNotAfter()); } String identity = BouncyCastleUtil.getIdentity( bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain))); this.sourceName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); this.anonymity = false; } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = SERVER_START_DEL; } else { setDone(); } } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case SERVER_START_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL int delChar = this.conn.getInStream().read(); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); byte[] delChar = new byte[outByteBuff.remaining()]; outByteBuff.get(delChar, 0, delChar.length); /*DEL if (delChar != GSIConstants.DELEGATION_CHAR) { */ if (!Arrays.equals(delChar, DELEGATION_TOKEN)) { setDone(); break; } /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR, "noClientCert"); } X509Certificate tmpCert = (X509Certificate) chain[0]; /*DEL PureTLSUtil.convertCert((X509Cert)chain.lastElement()); */ byte[] req = generateCertRequest(tmpCert); /*DEL this.conn.getOutStream().write(req, 0, req.length); */ inByteBuff = ByteBuffer.wrap(req, 0, req.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.state = SERVER_END_DEL; break; case SERVER_END_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL X509Certificate certificate = CertUtil.loadCertificate(this.conn.getInStream()); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte[] buf = new byte[outByteBuff.remaining()]; outByteBuff.get(buf, 0, buf.length); ByteArrayInputStream inStream = new ByteArrayInputStream(buf, 0, buf.length); CertificateFactory cf = null; X509Certificate certificate = null; try { cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate(inStream); } finally { inStream.close(); } if (logger.isTraceEnabled()) { logger.trace("Received delegated cert: " + certificate.toString()); } verifyDelegatedCert(certificate); /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); int chainLen = chain.length; X509Certificate[] newChain = new X509Certificate[chainLen + 1]; newChain[0] = bcConvert((X509Certificate) certificate); for (int i = 0; i < chainLen; i++) { /*DEL newChain[i+1] = PureTLSUtil.convertCert((X509Cert)chain.elementAt(chainLen - 1 - i)); */ newChain[i + 1] = bcConvert((X509Certificate) chain[i]); } X509Credential proxy = new X509Credential(this.keyPair.getPrivate(), newChain); this.delegCred = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } setDone(); break; default: throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { // Likely BUFFER_UNDERFLOW; save the // inByteBuff bytes here like in the unwrap() case logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } logger.debug("exit acceptSecContext"); /*DEL return (this.out.size() > 0) ? this.out.toByteArray() : null; */ if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte[] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; }
From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegateTest.java
@Test public void testIssueDelegateWithInvalidCert2() throws CertificateException { IssueDelegate id = new IssueDelegate(); assertNotNull(id);// w ww . j av a 2s . co m CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(CERT_DATA.getBytes()))); JAXBElement<X509Certificate> jX509Certificate = new JAXBElement<X509Certificate>( QName.valueOf("X509Certificate"), X509Certificate.class, x509Certificate); // JAXBElement<byte[]> jX509Certificate = new // JAXBElement<byte[]>(QName.valueOf("X509Certificate"), byte[].class, // CERT_DATA.getBytes()); X509DataType x509DataType = new X509DataType(); x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().add(jX509Certificate); JAXBElement<X509DataType> jX509DataType = new JAXBElement<X509DataType>(QName.valueOf("X509Data"), X509DataType.class, x509DataType); KeyInfoType keyInfoType = new KeyInfoType(); keyInfoType.getContent().add(jX509DataType); JAXBElement<KeyInfoType> jKeyInfoType = new JAXBElement<KeyInfoType>(QName.valueOf("KeyInfo"), KeyInfoType.class, keyInfoType); UseKeyType useKeyType = new UseKeyType(); useKeyType.setAny(jKeyInfoType); JAXBElement<UseKeyType> jUseKeyType = new JAXBElement<UseKeyType>(QName.valueOf("UseKey"), UseKeyType.class, useKeyType); EasyMock.expect(requestMock.getAny()).andStubReturn(Arrays.asList((Object) jUseKeyType)); EasyMock.replay(requestMock); EasyMock.expect(passwordCallbackMock.resetUsername()).andReturn(null); EasyMock.expect(passwordCallbackMock.resetPassword()).andReturn("joespassword"); EasyMock.replay(passwordCallbackMock); TokenProvider tp1 = new Saml1TokenProvider(); TokenProvider tp2 = new Saml2TokenProvider(); id.setTokenProviders(Arrays.asList(tp1, tp2)); id.setPasswordCallback(passwordCallbackMock); try { id.issue(requestMock); fail("CertificateException should be thrown"); } catch (Exception e) { } verify(requestMock); }
From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java
/** * Gets the CRLs returned by the MyProxy server. * * @return CRLs or null if none available *///w w w . j a v a 2 s . c om public X509CRL[] getCRLs() throws CertificateException { if (trustrootData == null) return null; CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); Collection<X509CRL> c = new ArrayList<X509CRL>(trustrootData.length); for (int i = 0; i < trustrootData.length; i++) { String crlData = trustrootData[i]; int index = crlData.indexOf("-----BEGIN X509 CRL-----"); if (index >= 0) { crlData = crlData.substring(index); ByteArrayInputStream inputStream = new ByteArrayInputStream(crlData.getBytes()); try { X509CRL crl = (X509CRL) certFactory.generateCRL(inputStream); c.add(crl); } catch (Exception e) { getMlf().warn(this.trustrootFilenames[i] + " can not be parsed as an X509CRL."); } } } if (c.isEmpty()) return null; return c.toArray(new X509CRL[0]); }
From source file:test.integ.be.agiv.security.IPSTSTest.java
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore, DateTime notAfter) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException { PublicKey subjectPublicKey = keyPair.getPublic(); PrivateKey issuerPrivateKey = keyPair.getPrivate(); String signatureAlgorithm = "SHA1WithRSAEncryption"; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset();/*from ww w . ja va 2s .com*/ certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); certificateGenerator.setNotBefore(notBefore.toDate()); certificateGenerator.setNotAfter(notAfter.toDate()); X509Principal issuerDN = new X509Principal(subjectDn); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(new X509Principal(subjectDn)); certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom())); certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; issuerPublicKey = subjectPublicKey; certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); X509Certificate certificate; certificate = certificateGenerator.generate(issuerPrivateKey); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); return certificate; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Load Taverna's Truststore from a file on a disk. If the Truststore does * not already exist, a new empty one will be created and contents of Java's * truststore located in <JAVA_HOME>/lib/security/cacerts will be copied * over to the Truststore./*from w ww. j a va 2 s. co m*/ */ private void loadTruststore() throws CMException { if (truststore != null) return; try { /* * Try to create Taverna's Truststore as Bouncy Castle UBER-type * keystore. */ truststore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { /* * The requested keystore type is not available from security * providers. */ throw new CMException("Failed to instantiate Taverna's Truststore", ex); } if (truststoreFile.exists()) { /* * If the Truststore file already exists, open it and load the * Truststore */ try (FileInputStream fis = new FileInputStream(truststoreFile)) { // Load the Truststore from the file truststore.load(fis, masterPassword.toCharArray()); } catch (Exception ex) { /* Clear out things that are useless/hindering now */ truststore = null; masterPassword = null; String exMessage = "Failed to load Taverna's Truststore from " + truststoreFile.getAbsolutePath() + ". Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } deleteRevokedCertificates(); } else { /* * Otherwise create a new empty Truststore and load it with certs * from Java's truststore. */ File javaTruststoreFile = new File(System.getProperty("java.home"), "lib/security/cacerts"); KeyStore javaTruststore = null; // Java's truststore is of type "JKS" - try to load it try { javaTruststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the // provider throw new CMException( "Failed to instantiate a 'JKS'-type keystore " + "for reading Java's truststore.", ex); } boolean loadedJavaTruststore = false; /* * Load Java's truststore from the file - try with the default Java * truststore passwords. */ for (String password : defaultTrustStorePasswords) { logger.info("Trying to load Java truststore using password: " + password); try (FileInputStream fis = new FileInputStream(javaTruststoreFile)) { javaTruststore.load(fis, password.toCharArray()); loadedJavaTruststore = true; break; } catch (IOException ioex) { /* * If there is an I/O or format problem with the keystore * data, or if the given password was incorrect. (Thank you * Sun, now I can't know if it is the file or the * password..) */ logger.info(String.format( "Failed to load the Java truststore to copy " + "over certificates using default password: " + "%s from %s", password, javaTruststoreFile)); } catch (NoSuchAlgorithmException e) { logger.error("Unknown encryption algorithm " + "while loading Java truststore from " + javaTruststoreFile, e); break; } catch (CertificateException e) { logger.error("Certificate error while " + "loading Java truststore from " + javaTruststoreFile, e); break; } } /* * Default Java truststore passwords failed - possibly the user has * changed it. Ask the Java truststore password providers if they * can help - this will typically pop up a dialog to ask the user if * we are in a graphical environment. If not, we will simply not * copy the default truststore certificates into Credential * Manager's Truststore. */ if (!loadedJavaTruststore && !loadJavaTruststoreUsingPasswordProviders(javaTruststore, javaTruststoreFile)) { String error = "Credential manager failed to load" + " certificates from Java's truststore."; String help = "Try using the system property -D" + PROPERTY_TRUSTSTORE_PASSWORD + "=TheTrustStorePassword"; logger.error(error + " " + help); // FIXME Writes to standard error! System.err.println(error); System.err.println(help); } // Create a new empty Truststore for Taverna try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.load(null, null); if (loadedJavaTruststore) { // Copy certificates into Taverna's Truststore from // Java's truststore. Enumeration<String> aliases = javaTruststore.aliases(); while (aliases.hasMoreElements()) { Certificate certificate = javaTruststore.getCertificate(aliases.nextElement()); if (certificate instanceof X509Certificate) truststore.setCertificateEntry( createTrustedCertificateAlias((X509Certificate) certificate), certificate); } } // Insert special trusted CA certificates logger.info( "Loading certificates of trusted CAs so as to establish trust into our services such as BioCatalogue, BiodiversityCatalogue, heater, etc."); CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (URL trustedCertURL : getSpecialTrustedCertificates()) // Load the certificate (possibly a chain) from the // stream try (InputStream stream = trustedCertURL.openStream()) { for (Certificate c : cf.generateCertificates(stream)) truststore.setCertificateEntry(createTrustedCertificateAlias((X509Certificate) c), c); } catch (Exception cex) { logger.error("Failed to insert trusted certificate entry in the Truststore", cex); } // Immediately save the new Truststore to the file truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { /* * make truststore null as it was just created but failed to * save so we should retry next time */ truststore = null; throw new CMException("Failed to generate new empty Taverna's Truststore", ex); } } /* * Taverna distro for MAC contains info.plist file with some Java system * properties set to use the Keychain which clashes with what we are * setting here so we need to clear them. */ System.clearProperty(PROPERTY_TRUSTSTORE_TYPE); System.clearProperty(PROPERTY_TRUSTSTORE_PROVIDER); /* * Not quite sure why we still need to set these two properties since we * are creating our own SSLSocketFactory with our own TrustManager that * uses Taverna's Truststore, but seem like after Taverna starts up and * the first time it needs SSLSocketFactory for HTTPS connection it is * still using the default Java's truststore unless these properties are * set. Set the system property "javax.net.ssl.Truststore" to use * Taverna's truststore. */ /* * Axis 1 likes reading from these properties but seems to work as well * with Taverna's SSLSocetFactory as well. We do not want to expose * these as they can be read from Beanshells. */ // System.setProperty(PROPERTY_TRUSTSTORE, truststoreFile.getAbsolutePath()); // System.setProperty(PROPERTY_TRUSTSTORE_PASSWORD, masterPassword); System.clearProperty(PROPERTY_TRUSTSTORE); System.clearProperty(PROPERTY_TRUSTSTORE_PASSWORD); }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Load Taverna's Truststore from a file on a disk. If the Truststore does * not already exist, a new empty one will be created and contents of Java's * truststore located in <JAVA_HOME>/lib/security/cacerts will be copied * over to the Truststore./*from w w w. jav a 2 s . c o m*/ */ private void loadTruststore() throws CMException { if (truststore == null) { try { // Try to create Taverna's Truststore as Bouncy Castle UBER-type // keystore. truststore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from security // providers. throw new CMException("Failed to instantiate Taverna's Truststore", ex); } if (truststoreFile.exists()) { // If the Truststore file already exists, open it and load the // Truststore try (FileInputStream fis = new FileInputStream(truststoreFile)) { // Load the Truststore from the file truststore.load(fis, masterPassword.toCharArray()); // Delete the old revoked or unnecessary BioCatalogue, // BiodiversityCatalogue and heater's certificates, if present deleteRevokedCertificates(); } catch (Exception ex) { /* Clear out things that are useless/hindering now */ truststore = null; masterPassword = null; String exMessage = "Failed to load Taverna's Truststore from " + truststoreFile.getAbsolutePath() + ". Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } } else { /* * Otherwise create a new empty Truststore and load it with * certs from Java's truststore. */ File javaTruststoreFile = new File(System.getProperty("java.home"), "lib/security/cacerts"); KeyStore javaTruststore = null; // Java's truststore is of type "JKS" - try to load it try { javaTruststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the // provider throw new CMException( "Failed to instantiate a 'JKS'-type keystore " + "for reading Java's truststore.", ex); } boolean loadedJavaTruststore = false; /* * Load Java's truststore from the file - try with the default * Java truststore passwords. */ for (String password : defaultTrustStorePasswords) { logger.info("Trying to load Java truststore using password: " + password); try (FileInputStream fis = new FileInputStream(javaTruststoreFile)) { javaTruststore.load(fis, password.toCharArray()); loadedJavaTruststore = true; break; } catch (IOException ioex) { /* * If there is an I/O or format problem with the * keystore data, or if the given password was incorrect * (Thank you Sun, now I can't know if it is the file or * the password..) */ logger.info(String.format( "Failed to load the Java truststore to copy " + "over certificates using default password: " + "%s from %s", password, javaTruststoreFile)); } catch (NoSuchAlgorithmException e) { logger.error("Unknown encryption algorithm " + "while loading Java truststore from " + javaTruststoreFile, e); break; } catch (CertificateException e) { logger.error( "Certificate error while " + "loading Java truststore from " + javaTruststoreFile, e); break; } } /* * Default Java truststore passwords failed - possibly the user * has changed it. Ask the Java truststore password providers if * they can help - this will typically pop up a dialog to ask * the user if we are in a graphical environment. If not, we * will simply not copy the default truststore certificates into * Credential Manager's Truststore. */ if (!loadedJavaTruststore) if (!(loadJavaTruststoreUsingPasswordProviders(javaTruststore, javaTruststoreFile))) { String error = "Credential manager failed to load" + " certificates from Java's truststore."; String help = "Try using the system property -D" + PROPERTY_TRUSTSTORE_PASSWORD + "=TheTrustStorePassword"; logger.error(error + " " + help); // FIXME Writes to standard error! System.err.println(error); System.err.println(help); } // Create a new empty Truststore for Taverna try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.load(null, null); if (loadedJavaTruststore) { // Copy certificates into Taverna's Truststore from // Java's truststore. Enumeration<String> aliases = javaTruststore.aliases(); while (aliases.hasMoreElements()) { Certificate certificate = javaTruststore.getCertificate(aliases.nextElement()); if (certificate instanceof X509Certificate) truststore.setCertificateEntry( createTrustedCertificateAlias((X509Certificate) certificate), certificate); } } // Insert special trusted CA certificates logger.info( "Loading certificates of trusted CAs so as to establish trust into our services such as BioCatalogue, BiodiversityCatalogue, heater, etc."); CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (URL trustedCertURL : getSpecialTrustedCertificates()) // Load the certificate (possibly a chain) from the // stream try (InputStream stream = trustedCertURL.openStream()) { for (Certificate c : cf.generateCertificates(stream)) truststore.setCertificateEntry(createTrustedCertificateAlias((X509Certificate) c), c); } catch (Exception cex) { logger.error("Failed to insert trusted certificate entry in the Truststore", cex); } // Immediately save the new Truststore to the file truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { /* * make truststore null as it was just created but failed to * save so we should retry next time */ truststore = null; throw new CMException("Failed to generate new empty Taverna's Truststore", ex); } } /* * Taverna distro for MAC contains info.plist file with some Java * system properties set to use the Keychain which clashes with what * we are setting here so we need to clear them. */ System.clearProperty(PROPERTY_TRUSTSTORE_TYPE); System.clearProperty(PROPERTY_TRUSTSTORE_PROVIDER); /* * Not quite sure why we still need to set these two properties * since we are creating our own SSLSocketFactory with our own * TrustManager that uses Taverna's Truststore, but seem like after * Taverna starts up and the first time it needs SSLSocketFactory * for HTTPS connection it is still using the default Java's * truststore unless these properties are set. Set the system * property "javax.net.ssl.Truststore" to use Taverna's truststore. */ /* * Axis 1 likes reading from these properties but seems to work as * well with Taverna's SSLSocetFactory as well. We do not want to * expose these as they can be read from Beanshells. */ // System.setProperty(PROPERTY_TRUSTSTORE, truststoreFile.getAbsolutePath()); // System.setProperty(PROPERTY_TRUSTSTORE_PASSWORD, masterPassword); System.clearProperty(PROPERTY_TRUSTSTORE); System.clearProperty(PROPERTY_TRUSTSTORE_PASSWORD); } }