List of usage examples for java.security.cert CertificateFactory getInstance
public static final CertificateFactory getInstance(String type) throws CertificateException
From source file:org.wso2.iot.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . */// w ww . ja v a2s . c o m public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) { Log.e(TAG, e.getMessage(), e); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:de.stklcode.jvault.connector.HTTPVaultConnectorOfflineTest.java
/** * Test constductors of the {@link HTTPVaultConnector} class. *//*from ww w . ja va 2s . com*/ @Test public void constructorTest() throws IOException, CertificateException { final String url = "https://vault.example.net/test/"; final String hostname = "vault.example.com"; final Integer port = 1337; final String prefix = "/custom/prefix/"; final Integer retries = 42; final String expectedNoTls = "http://" + hostname + "/v1/"; final String expectedCustomPort = "https://" + hostname + ":" + port + "/v1/"; final String expectedCustomPrefix = "https://" + hostname + ":" + port + prefix; X509Certificate trustedCaCert; try (InputStream is = getClass().getResourceAsStream("/tls/ca.pem")) { trustedCaCert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); } // Most basic constructor expects complete URL. HTTPVaultConnector connector = new HTTPVaultConnector(url); assertThat("Unexpected base URL", getPrivate(connector, "baseURL"), is(url)); // Now override TLS usage. connector = new HTTPVaultConnector(hostname, false); assertThat("Unexpected base URL with TLS disabled", getPrivate(connector, "baseURL"), is(expectedNoTls)); // Specify custom port. connector = new HTTPVaultConnector(hostname, true, port); assertThat("Unexpected base URL with custom port", getPrivate(connector, "baseURL"), is(expectedCustomPort)); // Specify custom prefix. connector = new HTTPVaultConnector(hostname, true, port, prefix); assertThat("Unexpected base URL with custom prefix", getPrivate(connector, "baseURL"), is(expectedCustomPrefix)); assertThat("Trusted CA cert set, but not specified", getPrivate(connector, "trustedCaCert"), is(nullValue())); // Provide custom SSL context. connector = new HTTPVaultConnector(hostname, true, port, prefix, trustedCaCert); assertThat("Unexpected base URL with custom prefix", getPrivate(connector, "baseURL"), is(expectedCustomPrefix)); assertThat("Trusted CA cert not filled correctly", getPrivate(connector, "trustedCaCert"), is(trustedCaCert)); // Specify number of retries. connector = new HTTPVaultConnector(url, trustedCaCert, retries); assertThat("Number of retries not set correctly", getPrivate(connector, "retries"), is(retries)); // Test TLS version (#22). assertThat("TLS version should be 1.2 if not specified", getPrivate(connector, "tlsVersion"), is("TLSv1.2")); // Now override. connector = new HTTPVaultConnector(url, trustedCaCert, retries, null, "TLSv1.1"); assertThat("Overridden TLS version 1.1 not correct", getPrivate(connector, "tlsVersion"), is("TLSv1.1")); }
From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java
/** * Verifies the signature using PKI./*ww w.j ava 2 s.co m*/ */ private boolean validateSignatureV2(Map<String, String> parameters, String urlEndPoint, String httpMethod) throws SignatureException { // 1. input validation. String signature = parameters.get(SIGNATURE_KEYNAME); if (signature == null) { throw new SignatureException("'signature' is missing from the parameters."); } String signatureMethod = parameters.get(SIGNATURE_METHOD_KEYNAME); if (signatureMethod == null) { throw new SignatureException("'signatureMethod' is missing from the parameters."); } String signatureAlgorithm = getSignatureAlgorithm(signatureMethod); if (signatureAlgorithm == null) { throw new SignatureException("'signatureMethod' present in parameters is invalid. " + "Valid signatureMethods are : 'RSA-SHA1'"); } String certificateUrl = parameters.get(CERTIFICATE_URL_KEYNAME); if (certificateUrl == null) { throw new SignatureException("'certificateUrl' is missing from the parameters."); } String certificate = getPublicKeyCertificateAsString(certificateUrl); if (certificate == null) { throw new SignatureException("public key certificate could not fetched from url: " + certificateUrl); } // 2. calculating the string to sign String stringToSign = EMPTY_STRING; try { URL url = new URL(urlEndPoint); String hostHeader = getHostHeader(url); String requestURI = getRequestURI(url); stringToSign = calculateStringToSignV2(parameters, httpMethod, hostHeader, requestURI); } catch (MalformedURLException e) { throw new SignatureException(e); } // 3. verify signature try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(certificate.getBytes())); Signature signatureInstance = Signature.getInstance(signatureAlgorithm); signatureInstance.initVerify(x509Certificate.getPublicKey()); signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding)); return signatureInstance.verify(Base64.decodeBase64(signature.getBytes())); } catch (CertificateException e) { throw new SignatureException(e); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } catch (InvalidKeyException e) { throw new SignatureException(e); } catch (UnsupportedEncodingException e) { throw new SignatureException(e); } }
From source file:org.candlepin.util.X509CRLEntryStreamTest.java
@Test public void testPemReadThroughBase64Stream() throws Exception { /* NB: Base64InputStream only takes base64. The "-----BEGIN X509 CRL-----" and * corresponding footer must be removed. Luckily in Base64InputStream stops the * minute it sees a padding character and our test file has some padding. Thus, * we don't need to worry about removing the footer. If the Base64 file didn't * require padding, I'm not sure what happens so the footer should be removed * somehow for real uses *///from ww w . ja v a 2s.co m InputStream referenceStream = new BufferedInputStream(new FileInputStream(pemFile)); byte[] header = "-----BEGIN X509 CRL-----".getBytes("ASCII"); Streams.readFully(referenceStream, header); referenceStream = new Base64InputStream(referenceStream); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRL referenceCrl = (X509CRL) cf.generateCRL(referenceStream); Set<BigInteger> referenceSerials = new HashSet<BigInteger>(); for (X509CRLEntry entry : referenceCrl.getRevokedCertificates()) { referenceSerials.add(entry.getSerialNumber()); } X509CRLEntryStream stream = new X509CRLEntryStream(derFile); try { Set<BigInteger> streamedSerials = new HashSet<BigInteger>(); while (stream.hasNext()) { streamedSerials.add(stream.next().getSerialNumber()); } assertEquals(referenceSerials, streamedSerials); } finally { referenceStream.close(); stream.close(); } }
From source file:JALPTest.java
/** * Creates a Producer using the given command line params. * * @param xml the ApplicationMetadataXML * @param socketPath a String which is the path to the socket * @param privateKeyPath a String which is the path to the private key in DER format * @param publicKeyPath a String which is the path to the public key in DER format * @param certPath a String which is the path to the certificate * @param hasDigest a Boolean, true to set a digest method in the producer * @return the created Producer/*w w w. java2s . c om*/ * @throws Exception */ private static Producer createProducer(ApplicationMetadataXML xml, String socketPath, String privateKeyPath, String publicKeyPath, String certPath, Boolean hasDigest) throws Exception { Producer producer = new Producer(xml); producer.setSocketFile(socketPath); if (privateKeyPath != null && !"".equals(privateKeyPath)) { File privateKeyFile = new File(privateKeyPath); DataInputStream privateDis = new DataInputStream(new FileInputStream(privateKeyFile)); byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()]; privateDis.readFully(privateKeyBytes); privateDis.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey = keyFactory.generatePrivate(privateKs); File publicKeyFile = new File(publicKeyPath); DataInputStream publicDis = new DataInputStream(new FileInputStream(publicKeyFile)); byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()]; publicDis.readFully(publicKeyBytes); publicDis.close(); KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey = keyFactory.generatePublic(publicKs); producer.setPrivateKey(privateKey); producer.setPublicKey(publicKey); } if (certPath != null && !"".equals(certPath)) { InputStream inputStream = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); inputStream.close(); producer.setCertificate(cert); } if (hasDigest) { producer.setDigestMethod(DMType.SHA256); } return producer; }
From source file:org.jscep.server.ScepServlet.java
/** * {@inheritDoc}// w w w. j a v a2 s .co m */ @SuppressWarnings("unchecked") @Override public final void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { byte[] body = getMessageBytes(req); final Operation op; try { op = getOperation(req); if (op == null) { // The operation parameter must be set. res.setStatus(HttpServletResponse.SC_BAD_REQUEST); Writer writer = res.getWriter(); writer.write("Missing \"operation\" parameter."); writer.flush(); return; } } catch (IllegalArgumentException e) { // The operation was not recognised. res.setStatus(HttpServletResponse.SC_BAD_REQUEST); Writer writer = res.getWriter(); writer.write("Invalid \"operation\" parameter."); writer.flush(); return; } LOGGER.debug("Incoming Operation: " + op); final String reqMethod = req.getMethod(); if (op == Operation.PKI_OPERATION) { if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) { // PKIOperation must be sent using GET or POST res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); res.addHeader("Allow", GET + ", " + POST); return; } } else { if (!reqMethod.equals(GET)) { // Operations other than PKIOperation must be sent using GET res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); res.addHeader("Allow", GET); return; } } LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op); if (op == Operation.GET_CA_CAPS) { try { LOGGER.debug("Invoking doGetCaCaps"); doGetCaCaps(req, res); } catch (Exception e) { throw new ServletException(e); } } else if (op == Operation.GET_CA_CERT) { try { LOGGER.debug("Invoking doGetCaCert"); doGetCaCert(req, res); } catch (Exception e) { throw new ServletException(e); } } else if (op == Operation.GET_NEXT_CA_CERT) { try { LOGGER.debug("Invoking doGetNextCaCert"); doGetNextCaCert(req, res); } catch (Exception e) { throw new ServletException(e); } } else if (op == Operation.PKI_OPERATION) { // PKIOperation res.setHeader("Content-Type", "application/x-pki-message"); CMSSignedData sd; try { sd = new CMSSignedData(body); } catch (CMSException e) { throw new ServletException(e); } Store reqStore = sd.getCertificates(); Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null); CertificateFactory factory; try { factory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new ServletException(e); } X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert; try { reqCert = (X509Certificate) factory.generateCertificate(bais); } catch (CertificateException e) { throw new ServletException(e); } PkiMessage<?> msg; try { PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(), getRecipientKey()); PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder); msg = decoder.decode(sd); } catch (MessageDecodingException e) { LOGGER.error("Error decoding request", e); throw new ServletException(e); } LOGGER.debug("Processing message {}", msg); MessageType msgType = msg.getMessageType(); Object msgData = msg.getMessageData(); Nonce senderNonce = Nonce.nextNonce(); TransactionId transId = msg.getTransactionId(); Nonce recipientNonce = msg.getSenderNonce(); CertRep certRep; if (msgType == MessageType.GET_CERT) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X500Name principal = iasn.getName(); final BigInteger serial = iasn.getSerialNumber().getValue(); try { List<X509Certificate> issued = doGetCert(principal, serial); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (OperationFailureException e) { certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.GET_CERT_INITIAL) { final IssuerAndSubject ias = (IssuerAndSubject) msgData; final X500Name issuer = X500Name.getInstance(ias.getIssuer()); final X500Name subject = X500Name.getInstance(ias.getSubject()); try { List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (OperationFailureException e) { certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.GET_CRL) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X500Name issuer = iasn.getName(); final BigInteger serialNumber = iasn.getSerialNumber().getValue(); try { LOGGER.debug("Invoking doGetCrl"); CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber)); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } catch (OperationFailureException e) { LOGGER.error("Error executing GetCRL request", e); certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { LOGGER.error("Error executing GetCRL request", e); throw new ServletException(e); } } else if (msgType == MessageType.PKCS_REQ) { final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData; try { LOGGER.debug("Invoking doEnrol"); List<X509Certificate> issued = doEnrol(certReq, transId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (OperationFailureException e) { certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { throw new ServletException(e); } } else { throw new ServletException("Unknown Message for Operation"); } PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede"); PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(), getSignerCertificateChain(), envEncoder); CMSSignedData signedData; try { signedData = encoder.encode(certRep); } catch (MessageEncodingException e) { LOGGER.error("Error decoding response", e); throw new ServletException(e); } res.getOutputStream().write(signedData.getEncoded()); res.getOutputStream().close(); } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation"); } }
From source file:com.vangent.hieos.services.sts.util.STSUtil.java
/** * * @param cert/* w w w.j a v a 2 s.c o m*/ * @param trustStore * @throws STSException */ public static void validateCertificate(X509Certificate cert, KeyStore trustStore) throws STSException { try { // To check the validity of the dates cert.checkValidity(); } catch (CertificateExpiredException ex) { throw new STSException("Certificate expired: " + ex.getMessage()); } catch (CertificateNotYetValidException ex) { throw new STSException("Certificate not yet valid: " + ex.getMessage()); } // Check the chain. try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List<X509Certificate> mylist = new ArrayList<X509Certificate>(); mylist.add(cert); CertPath cp = cf.generateCertPath(mylist); PKIXParameters params = new PKIXParameters(trustStore); // FIXME: Add revocation checking. params.setRevocationEnabled(false); CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); PKIXCertPathValidatorResult pkixCertPathValidatorResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params); if (logger.isDebugEnabled()) { logger.debug(pkixCertPathValidatorResult); } } catch (Exception ex) { throw new STSException("Exception while validating Certificate: " + ex.getMessage()); } }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int) *//*from w w w. ja va2 s .c om*/ public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", subjectData); DEBUGGER.debug("Value: {}", validityPeriod); DEBUGGER.debug("Value: {}", keySize); } final File rootDirectory = certConfig.getRootDirectory(); final String signatureAlgorithm = certConfig.getSignatureAlgorithm(); final String certificateAlgorithm = certConfig.getCertificateAlgorithm(); final File privateKeyDirectory = FileUtils .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0)); final File publicKeyDirectory = FileUtils .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0)); final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0)); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0)); final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O=" + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C=" + subjectData.get(5) + ",E=" + subjectData.get(6)); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm); DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm); DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory); DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory); DEBUGGER.debug("csrDirectory: {}", csrDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("x500Name: {}", x500Name); } File csrFile = null; JcaPEMWriter csrPemWriter = null; JcaPEMWriter publicKeyWriter = null; JcaPEMWriter privateKeyWriter = null; FileOutputStream csrFileStream = null; FileOutputStream keyStoreStream = null; FileOutputStream publicKeyFileStream = null; FileOutputStream privateKeyFileStream = null; OutputStreamWriter csrFileStreamWriter = null; OutputStreamWriter privateKeyStreamWriter = null; OutputStreamWriter publicKeyStreamWriter = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm); keyGenerator.initialize(keySize, random); if (DEBUG) { DEBUGGER.debug("KeyGenerator: {}", keyGenerator); } KeyPair keyPair = keyGenerator.generateKeyPair(); if (DEBUG) { DEBUGGER.debug("KeyPair: {}", keyPair); } if (keyPair != null) { final Signature sig = Signature.getInstance(signatureAlgorithm); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); if (DEBUG) { DEBUGGER.debug("Signature: {}", sig); DEBUGGER.debug("PrivateKey: {}", privateKey); DEBUGGER.debug("PublicKey: {}", publicKey); } sig.initSign(privateKey, random); ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); if (DEBUG) { DEBUGGER.debug("ContentSigner: {}", signGen); } Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityPeriod); if (DEBUG) { DEBUGGER.debug("Calendar: {}", expiry); } CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert); } keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate( new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())))); keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(), certFactory.generateCertificate(new FileInputStream( FileUtils.getFile(certConfig.getIntermediateCertificateFile())))); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name, publicKey); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder); } PKCS10CertificationRequest csr = builder.build(signGen); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequest: {}", csr); } // write private key File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("privateKeyFile: {}", privateKeyFile); } if (!(privateKeyFile.createNewFile())) { throw new IOException("Failed to store private file"); } privateKeyFileStream = new FileOutputStream(privateKeyFile); privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream); if (DEBUG) { DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream); DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter); } privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter); privateKeyWriter.writeObject(privateKey); privateKeyWriter.flush(); privateKeyStreamWriter.flush(); privateKeyFileStream.flush(); // write public key File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("publicKeyFile: {}", publicKeyFile); } if (!(publicKeyFile.createNewFile())) { throw new IOException("Failed to store public key file"); } publicKeyFileStream = new FileOutputStream(publicKeyFile); publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter); publicKeyWriter.writeObject(publicKey); publicKeyWriter.flush(); publicKeyStreamWriter.flush(); publicKeyFileStream.flush(); // write csr csrFile = FileUtils .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT); if (DEBUG) { DEBUGGER.debug("csrFile: {}", csrFile); } if (!(csrFile.createNewFile())) { throw new IOException("Failed to store CSR file"); } csrFileStream = new FileOutputStream(csrFile); csrFileStreamWriter = new OutputStreamWriter(csrFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } csrPemWriter = new JcaPEMWriter(csrFileStreamWriter); csrPemWriter.writeObject(csr); csrPemWriter.flush(); csrFileStreamWriter.flush(); csrFileStream.flush(); File keyStoreFile = FileUtils .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType()); if (DEBUG) { DEBUGGER.debug("keyStoreFile: {}", keyStoreFile); } keyStoreStream = FileUtils.openOutputStream(keyStoreFile); if (DEBUG) { DEBUGGER.debug("keyStoreStream: {}", keyStoreStream); } keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(), issuerCert); keyStore.store(keyStoreStream, storePassword.toCharArray()); keyStoreStream.flush(); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } } else { throw new CertificateManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (InvalidKeyException ikx) { throw new CertificateManagementException(ikx.getMessage(), ikx); } catch (OperatorCreationException ocx) { throw new CertificateManagementException(ocx.getMessage(), ocx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } finally { if (csrFileStreamWriter != null) { IOUtils.closeQuietly(csrFileStreamWriter); } if (csrFileStream != null) { IOUtils.closeQuietly(csrFileStream); } if (csrPemWriter != null) { IOUtils.closeQuietly(csrPemWriter); } if (publicKeyFileStream != null) { IOUtils.closeQuietly(publicKeyFileStream); } if (publicKeyStreamWriter != null) { IOUtils.closeQuietly(publicKeyStreamWriter); } if (publicKeyWriter != null) { IOUtils.closeQuietly(publicKeyWriter); } if (privateKeyFileStream != null) { IOUtils.closeQuietly(privateKeyFileStream); } if (privateKeyStreamWriter != null) { IOUtils.closeQuietly(privateKeyStreamWriter); } if (privateKeyWriter != null) { IOUtils.closeQuietly(privateKeyWriter); } if (keyStoreStream != null) { IOUtils.closeQuietly(keyStoreStream); } } return csrFile; }
From source file:eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator.java
private boolean checkVriDict(PdfDictionary vriSigDictionary, boolean _vriVerificationresult, PAdESSignature pades, ValidationContext ctx, String hexHash) throws CertificateException, IOException, CRLException, OCSPException { boolean vriVerificationresult = _vriVerificationresult; if (vriSigDictionary == null) { LOG.info("Couldn't find the signature VRI identified by " + hexHash + " in the DSS"); vriVerificationresult = false;//from ww w .ja va 2 s. c o m } else { LOG.info("Found the signature VRI identified by " + hexHash + " in the DSS"); // Verify the certs in the VRI PdfArray vricert = vriSigDictionary.getAsArray(new PdfName("Cert")); if (vricert != null) { CertificateFactory factory = CertificateFactory.getInstance("X509"); List<X509Certificate> certs = new ArrayList<X509Certificate>(); for (int i = 0; i < vricert.size(); i++) { PdfStream stream = vricert.getAsStream(i); certs.add((X509Certificate) factory.generateCertificate( new ByteArrayInputStream(PdfReader.getStreamBytes((PRStream) stream)))); } vriVerificationresult &= everyCertificateValueAreThere(ctx, certs, pades.getSigningCertificate()); } // Verify the CRLs in the VRI PdfArray vricrl = vriSigDictionary.getAsArray(new PdfName("CRL")); if (vricrl != null) { CertificateFactory factory = CertificateFactory.getInstance("X509"); List<X509CRL> crls = new ArrayList<X509CRL>(); for (int i = 0; i < vricrl.size(); i++) { PdfStream stream = vricrl.getAsStream(i); crls.add((X509CRL) factory .generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes((PRStream) stream)))); } vriVerificationresult &= everyCRLValueOrRefAreThere(ctx, crls); } // Verify the OCSPs in the VRI PdfArray vriocsp = vriSigDictionary.getAsArray(new PdfName("OCSP")); if (vriocsp != null) { List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>(); for (int i = 0; i < vriocsp.size(); i++) { PdfStream stream = vriocsp.getAsStream(i); ocsps.add((BasicOCSPResp) new OCSPResp(PdfReader.getStreamBytes((PRStream) stream)) .getResponseObject()); } vriVerificationresult &= everyOCSPValueOrRefAreThere(ctx, ocsps); } } return vriVerificationresult; }
From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java
/** * Generate a socket factory using supplied key and trust stores *//* ww w .ja v a 2s. co m*/ protected SSLConnectionSocketFactory getSocketFactory() throws IOException { TrustManager[] trustManagers = null; KeyManager[] keyManagers = null; try { /* trust managers */ if (caCertificateFile != null) { KeyStore trustStore; int cn = 0; log.info("Setting x509 trust from " + caCertificateFile); TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream in = new FileInputStream(caCertificateFile); Collection certs = cf.generateCertificates(in); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); Iterator cit = certs.iterator(); while (cit.hasNext()) { X509Certificate cert = (X509Certificate) cit.next(); log.info(" adding " + cert.getSubjectX500Principal().toString()); System.out.println(" adding " + cert.getSubjectX500Principal().toString()); trustStore.setCertificateEntry("CACERT" + cn, cert); cn += 1; } tmf.init(trustStore); trustManagers = tmf.getTrustManagers(); } else { // no verification trustManagers = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { return; } public void checkServerTrusted(X509Certificate[] certs, String authType) { return; } } }; } /* key manager */ if (certificateFile != null && keyFile != null) { KeyStore keyStore; KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); FileInputStream in = new FileInputStream(certificateFile); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(in); PKCS1 pkcs = new PKCS1(); log.info("reading key file: " + keyFile); PrivateKey key = pkcs.readKey(keyFile); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain); kmf.init(keyStore, "pw".toCharArray()); keyManagers = kmf.getKeyManagers(); } /* socket factory */ SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagers, trustManagers, null); return new SSLConnectionSocketFactory(ctx); } catch (IOException e) { log.error("error reading cert or key error: " + e); } catch (KeyStoreException e) { log.error("keystore error: " + e); } catch (NoSuchAlgorithmException e) { log.error("sf error: " + e); } catch (KeyManagementException e) { log.error("sf error: " + e); } catch (CertificateException e) { log.error("sf error: " + e); } catch (UnrecoverableKeyException e) { log.error("sf error: " + e); } return null; }