List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:org.apache.james.transport.mailets.SMIMEDecrypt.java
private X509CertificateHolder from(X509Certificate certificate) throws MessagingException { try {//from w ww . jav a2s . c o m return new X509CertificateHolder(certificate.getEncoded()); } catch (CertificateEncodingException e) { throw new MessagingException("Error during the parsing of the certificate", e); } catch (IOException e) { throw new MessagingException("Error during the parsing of the certificate", e); } }
From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java
/** * Creates a SOAP message with a signature. * <p>/*from w w w. j a v a 2 s .c o m*/ * A valid SOAP message is required, this will be the message to be signed. * * @param pathBase * path to the SOAP message to sign * @param privateKeyAlias * alias for the private key * @param privateKeyPass * password for the private key * @param certificateAlias * alias for the certificate * @param keystore * key store for the signing * @return a singed SOAP message * @throws Exception * if any error occurs during the message creation */ public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias, final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception { Element root = null; String BaseURI = new ClassPathResource(pathBase).getURI().toString(); SOAPMessage soapMessage; Base64Converter base64 = new Base64Converter(); String token; Node binaryToken; X509Certificate cert; PrivateKey privateKey; XMLSignature sig; soapMessage = getMessageToSign(pathBase); // get the private key used to sign, from the keystore privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray()); cert = (X509Certificate) keystore.getCertificate(certificateAlias); // create basic structure of signature Document doc = toDocument(soapMessage); org.apache.xml.security.Init.init(); sig = getSignature(doc, BaseURI, cert, privateKey); // optional, but better root = doc.getDocumentElement(); root.normalize(); root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement()); token = base64.encode(cert.getEncoded()); binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0); binaryToken.setTextContent(token); // write signature to file XMLUtils.outputDOMc14nWithComments(doc, System.out); return toMessage(doc); }
From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java
/** * Creates a SOAP message with a signature. * <p>/*from w w w. ja va 2 s . c o m*/ * A valid SOAP message is required, this will be the message to be signed. * * @param pathBase * path to the SOAP message to sign * @param privateKeyAlias * alias for the private key * @param privateKeyPass * password for the private key * @param certificateAlias * alias for the certificate * @param keystore * key store for the signing * @return a singed SOAP message * @throws Exception * if any error occurs during the message creation */ public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias, final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception { Element root = null; final String BaseURI = new ClassPathResource(pathBase).getURI().toString(); SOAPMessage soapMessage; final Base64Converter base64 = new Base64Converter(); String token; Node binaryToken; X509Certificate cert; PrivateKey privateKey; XMLSignature sig; soapMessage = getMessageToSign(pathBase); // get the private key used to sign, from the keystore privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray()); cert = (X509Certificate) keystore.getCertificate(certificateAlias); // create basic structure of signature final Document doc = toDocument(soapMessage); org.apache.xml.security.Init.init(); sig = getSignature(doc, BaseURI, cert, privateKey); // optional, but better root = doc.getDocumentElement(); root.normalize(); root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement()); token = base64.encode(cert.getEncoded()); binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0); binaryToken.setTextContent(token); // write signature to file XMLUtils.outputDOMc14nWithComments(doc, System.out); return toMessage(doc); }
From source file:org.soasecurity.mutual.ssl.filter.MutualSSLFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.debug("Mutual SSL Filter is invoked."); X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); if (certs != null) { // client certificate must be first certificate in the chain X509Certificate clientCert = certs[0]; // encode certificate String certificateData = ""; try {/* ww w . j av a2 s . c om*/ certificateData = new String(Base64.encodeBase64(clientCert.getEncoded())); } catch (CertificateEncodingException e) { log.error("Error while encoding the certificate", e); } Principal principal = clientCert.getSubjectDN(); String subjectDN = principal.getName(); log.debug("Mutual Authentication is success full with subject : " + subjectDN); // creating new wrapper to set a new parameter X509HTTPServletWrapper wrapper = new X509HTTPServletWrapper((HttpServletRequest) request, subjectDN, certificateData); chain.doFilter(wrapper, response); } else { chain.doFilter(request, response); } }
From source file:be.fedict.eid.pkira.common.security.AbstractPkiRaAuthenticationResponseService.java
@Override public void validateServiceCertificate(SamlAuthenticationPolicy authenticationPolicy, List<X509Certificate> certificateChain) throws SecurityException { if (certificateChain == null || certificateChain.size() == 0) { throw new SecurityException("Missing certificate chain"); }/* ww w .jav a 2s . co m*/ X509Certificate certificate = certificateChain.get(0); MessageDigest md; try { md = MessageDigest.getInstance("SHA1"); md.update(certificate.getEncoded()); byte[] fp = md.digest(); log.info("Actual fingerprint: " + Hex.encodeHexString(fp)); String[] fingerprintConfig = getFingerprints(); if (fingerprintConfig == null || fingerprintConfig.length == 0) { log.warn("No fingerprint given"); return; } boolean ok = false; Hex hex = new Hex(); for (String fingerprint : fingerprintConfig) { log.info("Allowed fingerprint: " + fingerprint); byte[] fpConfig = (byte[]) hex.decode(fingerprint); ok |= java.util.Arrays.equals(fp, fpConfig); } if (!ok) { log.error("Signatures not correct."); throw new SecurityException("Signatures not correct."); } } catch (NoSuchAlgorithmException e) { log.error("No Such Algorithm", e); throw new SecurityException(e.getMessage()); } catch (CertificateEncodingException e) { log.error("Certificate Encoding Exception", e); throw new SecurityException(e.getMessage()); } catch (DecoderException e) { log.error("Fingerprint decode problem", e); throw new SecurityException(e.getMessage()); } catch (Throwable e) { log.error("Exception during service certificate validation", e); throw new SecurityException(e.getMessage()); } }
From source file:net.jmhertlein.mcanalytics.plugin.daemon.request.AuthenticationRequestHandler.java
private boolean signClientKey(JSONObject request, JSONObject response) { String username = request.getString("username"); PKCS10CertificationRequest csr;//w w w .j a v a 2 s . c o m try { csr = new PKCS10CertificationRequest(Base64.decodeBase64(request.getString("csr"))); } catch (IOException ex) { return false; } Set<String> names = SSLUtil.getCNs(csr.getSubject()); if (names.size() == 1 && names.contains(username)) { X509Certificate clientCert = SSLUtil.fulfillCertRequest(serverKey, serverCert, csr, false); try { response.put("cert", Base64.encodeBase64String(clientCert.getEncoded())); response.put("ca", Base64.encodeBase64String(serverCert.getEncoded())); return true; } catch (CertificateEncodingException ex) { Logger.getLogger(AuthenticationRequestHandler.class.getName()).log(Level.SEVERE, null, ex); return false; } } else { return false; } }
From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java
/** * Create a PKCS #10 certificate signing request (CSR) using the supplied * certificate, private key and signature algorithm. * * @param cert/*from w ww . j a v a 2 s.c o m*/ * The certificate * @param privateKey * The private key * @param signatureType * Signature * @param challenge * Challenge, optional, pass null if not required * @param unstructuredName * An optional company name, pass null if not required * @param useExtensions * Use extensions from cert for extensionRequest attribute? * @throws CryptoException * If there was a problem generating the CSR * @return The CSR */ public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException { try { JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder( cert.getSubjectX500Principal(), cert.getPublicKey()); // add challenge attribute if (challenge != null) { // PKCS#9 2.0: SHOULD use UTF8String encoding csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge)); } if (unstructuredName != null) { csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName)); } if (useExtensions) { // add extensionRequest attribute with all extensions from the certificate Certificate certificate = Certificate.getInstance(cert.getEncoded()); Extensions extensions = certificate.getTBSCertificate().getExtensions(); if (extensions != null) { csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive()); } } // fall back to bouncy castle provider if given provider does not support the requested algorithm if (provider != null && provider.getService("Signature", signatureType.jce()) == null) { provider = new BouncyCastleProvider(); } ContentSigner contentSigner = null; if (provider == null) { contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey); } else { contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider) .build(privateKey); } PKCS10CertificationRequest csr = csrBuilder.build(contentSigner); if (!verifyCsr(csr)) { throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message")); } return csr; } catch (CertificateEncodingException e) { throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e); } catch (OperatorCreationException e) { throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e); } }
From source file:org.nimbustools.ctxbroker.security.CertificateAuthority.java
protected X509Certificate signNewCertificate(String cnString, PublicKey pubkey, Calendar expires) throws SignatureException, InvalidKeyException, CertificateException, IOException { this.setGenerator(this.getTargetDN(cnString), pubkey, expires.getTime()); X509Certificate x509 = this.certGen.generateX509Certificate(this.caPrivate); InputStream in = new ByteArrayInputStream(x509.getEncoded()); X509Certificate x509Cert = (X509Certificate) this.factory.generateCertificate(in); X500Principal subjectDN = x509Cert.getSubjectX500Principal(); String DN = subjectDN.getName(X500Principal.RFC2253); String globusDN = CertUtil.toGlobusID(DN, false); String msg = "Created new certificate with DN (RFC2253) = '" + DN + "' and Globus style DN = '" + globusDN + "'"; logger.trace(msg);/*w w w. ja va 2 s .c o m*/ return x509Cert; }
From source file:net.firejack.platform.installation.processor.InstallSlaveProcessor.java
@Override public void onApplicationEvent(InstallSlaveEvent event) { File keystore = InstallUtils.getKeyStore(); String url = OpenFlameConfig.MASTER_URL.getValue(); String admin = OpenFlameConfig.APP_ADMIN_NAME.getValue(); String password = OpenFlameConfig.APP_ADMIN_PASSWORD.getValue(); try {//from www .ja va2s .com if (keystore.exists()) { X500Name info = KeyUtils.getInfo(keystore); url = info.getDomain(); } String hostName = InetAddress.getLocalHost().getHostName(); KeyPair keyPair = KeyUtils.generate(keystore); if (keyPair == null) { throw new IllegalStateException("Key not found"); } X509Certificate certificate = KeyUtils.generateCertificate(url, 1, keyPair); if (StringUtils.isBlank(password)) { String cert = new String(Base64.encode(certificate.getEncoded())); OPFEngine.init(url, OpenFlame.PACKAGE, hostName, cert); } else { OPFEngine.init(url, admin, password); } ServerNodeConfig config = new ServerNodeConfig(); config.setServerName(hostName); // config.setServerName(hostName + "_slave"); //TODO [CLUSTER] don't commit this line config.setHost(InetAddress.getLocalHost().getHostAddress()); config.setPort(Integer.decode(OpenFlameConfig.PORT.getValue())); config.setNodeType(ServerNodeType.OPF_SLAVE); config.setLookup(OpenFlame.PACKAGE); config.setCert(certificate.getEncoded()); InputStream stream = OPFEngine.RegistryService.registerSlaveNode(config); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); byte[] decrypted = KeyUtils.decrypt(keyPair.getPrivate(), output.toByteArray()); Map<String, String> map = EnvironmentsUtils.convertFromXml(new ByteArrayInputStream(decrypted)); ConfigContainer.putAll(map); source.refreshDBProperties(); OPFEngine.release(); KeyUtils.add(keystore, keyPair, url); FileUtils.deleteQuietly(InstallUtils.getPropEnv()); } catch (Exception e) { logger.error(e); throw new IllegalStateException(e); } OPFEngine.initialize(); }
From source file:com.vmware.bdd.cli.http.DefaultTrustManager.java
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { String errorMsg = ""; InputStream in = null;/*from w ww. j ava2 s . c o m*/ OutputStream out = null; // load key store file try { char[] pwd = cliProperties.readKeyStorePwd(); File file = new File(KEY_STORE_FILE); if (file.exists() && file.isFile()) { keyStore.load(new FileInputStream(file), pwd); } else { //init an empty keystore keyStore.load(null, pwd); } // show certificate informations MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; String sha1Fingerprint = ""; SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy/MM/dd"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); md5Fingerprint = ByteArrayUtils.byteArrayToHexString(md5.digest()); sha1Fingerprint = ByteArrayUtils.byteArrayToHexString(sha1.digest()); if (keyStore.getCertificate(md5Fingerprint) != null) { if (i == chain.length - 1) { return; } else { continue; } } System.out.println(); System.out.println("Server Certificate"); System.out.println("================================================================"); System.out.println("Subject: " + cert.getSubjectDN()); System.out.println("Issuer: " + cert.getIssuerDN()); System.out.println("SHA Fingerprint: " + sha1Fingerprint); System.out.println("MD5 Fingerprint: " + md5Fingerprint); System.out.println("Issued on: " + dateFormate.format(cert.getNotBefore())); System.out.println("Expires on: " + dateFormate.format(cert.getNotAfter())); System.out.println("Signature: " + cert.getSignature()); System.out.println(); if (checkExpired(cert.getNotBefore(), cert.getNotAfter())) { throw new CertificateException("The security certificate has expired."); } ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setPrompt(Constants.PARAM_PROMPT_ADD_CERTIFICATE_MESSAGE); // Read user input String readMsg; if (RunWayConfig.getRunType().equals(RunWayConfig.RunType.MANUAL)) { readMsg = reader.readLine().trim(); } else { readMsg = "yes"; } if ("yes".equalsIgnoreCase(readMsg) || "y".equalsIgnoreCase(readMsg)) { { // add new certificate into key store file. keyStore.setCertificateEntry(md5Fingerprint, cert); out = new FileOutputStream(KEY_STORE_FILE); keyStore.store(out, pwd); CommonUtil.setOwnerOnlyReadWrite(KEY_STORE_FILE); // save keystore password cliProperties.saveKeyStorePwd(pwd); } } else { if (i == chain.length - 1) { throw new CertificateException("Could not find a valid certificate in the keystore."); } else { continue; } } } } catch (FileNotFoundException e) { errorMsg = "Cannot find the keystore file: " + e.getMessage(); } catch (NoSuchAlgorithmException e) { errorMsg = "SSL Algorithm not supported: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); errorMsg = "IO error: " + e.getMessage(); } catch (KeyStoreException e) { errorMsg = "Keystore error: " + e.getMessage(); } catch (ConfigurationException e) { errorMsg = "cli.properties access error: " + e.getMessage(); } finally { if (!CommandsUtils.isBlank(errorMsg)) { System.out.println(errorMsg); logger.error(errorMsg); } if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Input stream of serengeti.keystore close failed."); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of serengeti.keystore close failed."); } } } }