List of usage examples for java.security.cert Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java
public KeyStoreObjects getKeyStoreObjects(String reserver) { String keyStoreId = ""; File privateKsFile = new File(tempKeyStoreDir, reserver); File[] listFiles = new File(keyStoreDir).listFiles(noLeadingDot); int cnt = listFiles.length; int select = rng.nextInt(cnt); File selected;/*from www . j a va 2 s . co m*/ boolean success = false; // try to claim a ks file; try { selected = listFiles[select]; keyStoreId = selected.getName(); selected.renameTo(privateKsFile); success = privateKsFile.canRead(); } catch (Exception ex) { } // If not successful - generate a new key store if (!success) { createKeyStore(privateKsFile); keyStoreId = reserver; } try { KeyStore ks = getKeyStore(privateKsFile, keyStoreId); PrivateKey pk = (PrivateKey) ks.getKey(K_NAME, getKsPass(keyStoreId)); Certificate cert = ks.getCertificate(K_NAME); iaik.x509.X509Certificate x509cert = CertificateUtils.getCertificate(cert.getEncoded()); privateKsFile.delete(); return new KeyStoreObjects(pk, x509cert); } catch (Exception ex) { LOG.log(Level.WARNING, null, ex); privateKsFile.delete(); return null; } }
From source file:ddf.security.samlp.SimpleSignTest.java
@Before public void setUp() throws Exception { encryptionService = mock(PasswordEncryptor.class); systemCrypto = new SystemCrypto("encryption.properties", "signature.properties", encryptionService); simpleSign = new SimpleSign(systemCrypto); cannedResponse = Resources.toString(Resources.getResource(getClass(), "/SAMLResponse.xml"), Charsets.UTF_8); //Normally you would have the cert in a string already but for this test we will have to pull it out of the jks file Certificate cert = ((Merlin) systemCrypto.getSignatureCrypto()).getKeyStore().getCertificate("dsa"); StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("CERTIFICATE", cert.getEncoded())); pemWriter.flush();// ww w .jav a2s .com dsaCert = writer.toString().replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", ""); }
From source file:org.ejbca.extra.db.CardRenewalResponse.java
/** * Default constructor that should be used. * /*from w w w.java 2s . c om*/ */ public CardRenewalResponse(long requestId, boolean success, String failinfo, Certificate authcert, Certificate signcert) { super(requestId, success, failinfo); try { data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE)); data.put(VERSION, Float.valueOf(LATEST_VERSION)); if (authcert != null) { String certstring = new String(Base64.encode(authcert.getEncoded())); data.put(AUTHCERT, certstring); } if (signcert != null) { String certstring = new String(Base64.encode(signcert.getEncoded())); data.put(SIGNCERT, certstring); } } catch (CertificateEncodingException e) { log.error("Certificate encoding failed", e); } }
From source file:com.fine47.http.SecureSocketFactory.java
private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); ActivityHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Found expired SSL certificate in this store: " + factoryId); }//from www . ja v a 2 s . c o m // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; // Get the public key. publicKey = rootca.getPublicKey(); sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid"); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid"); } else try { for (X509Certificate cert : chain) { if (ActivityHttpClient.isDebugging()) { Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:"); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion()); Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); } // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's chain. cert.verify(publicKey); } } catch (InvalidKeyException ex) { error = ex; } catch (NoSuchAlgorithmException ex) { error = ex; } catch (NoSuchProviderException ex) { error = ex; } catch (SignatureException ex) { error = ex; } if (null != error && ActivityHttpClient.isDebugging()) { Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java
private CMPCertificate[] getCMPCerts(Certificate cert) throws CertificateEncodingException, IOException { ASN1InputStream ins = new ASN1InputStream(cert.getEncoded()); ASN1Primitive pcert = ins.readObject(); ins.close();//from w w w. j a va 2s .co m org.bouncycastle.asn1.x509.Certificate c = org.bouncycastle.asn1.x509.Certificate .getInstance(pcert.toASN1Primitive()); CMPCertificate[] res = { new CMPCertificate(c) }; return res; }
From source file:test.integ.be.agiv.security.BeIDTest.java
@Test public void testReadAuthnCert() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/* w w w . j a va 2s . co m*/ Certificate certificate = keyStore.getCertificate("Authentication"); LOG.debug("certificate: " + certificate); Certificate caCert = keyStore.getCertificate("CA"); LOG.debug("CA cert: " + caCert); Certificate rootCert = keyStore.getCertificate("Root"); LOG.debug("root cert: " + rootCert); File tmpFile = File.createTempFile("beid-authn-", ".der"); FileUtils.writeByteArrayToFile(tmpFile, certificate.getEncoded()); LOG.debug("cert file: " + tmpFile.getAbsolutePath()); File caTmpFile = File.createTempFile("gov-ca-", ".der"); FileUtils.writeByteArrayToFile(caTmpFile, caCert.getEncoded()); LOG.debug("ca cert file: " + caTmpFile.getAbsolutePath()); File rootTmpFile = File.createTempFile("root-ca-", ".der"); FileUtils.writeByteArrayToFile(rootTmpFile, rootCert.getEncoded()); LOG.debug("root cert file: " + rootTmpFile.getAbsolutePath()); }
From source file:org.archive.crawler.Heritrix.java
/** * Perform preparation to use an ad-hoc, created-as-necessary * certificate/keystore for HTTPS access. A keystore with new * cert is created if necessary, as adhoc.keystore in the working * directory. Otherwise, a preexisting adhoc.keystore is read * and the certificate fingerprint shown to assist in operator * browser-side verification.//from w w w. ja v a 2 s . com * @param startupOut where to report fingerprint */ protected void useAdhocKeystore(PrintStream startupOut) { try { File keystoreFile = new File(ADHOC_KEYSTORE); if (!keystoreFile.exists()) { String[] args = { "-keystore", ADHOC_KEYSTORE, "-storepass", ADHOC_PASSWORD, "-keypass", ADHOC_PASSWORD, "-alias", "adhoc", "-genkey", "-keyalg", "RSA", "-dname", "CN=Heritrix Ad-Hoc HTTPS Certificate", "-validity", "3650" }; // 10 yr validity KeyTool.main(args); } KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream inStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(keystoreFile)); keystore.load(inStream, ADHOC_PASSWORD.toCharArray()); Certificate cert = keystore.getCertificate("adhoc"); byte[] certBytes = cert.getEncoded(); byte[] sha1 = MessageDigest.getInstance("SHA1").digest(certBytes); startupOut.print("Using ad-hoc HTTPS certificate with fingerprint...\nSHA1"); for (byte b : sha1) { startupOut.print(String.format(":%02X", b)); } startupOut.println("\nVerify in browser before accepting exception."); } catch (Exception e) { // fatal, rethrow throw new RuntimeException(e); } }
From source file:it.anyplace.sync.core.security.KeystoreHandler.java
public void checkSocketCerificate(SSLSocket socket, String deviceId) throws SSLPeerUnverifiedException, CertificateException { SSLSession session = socket.getSession(); List<Certificate> certs = Arrays.asList(session.getPeerCertificates()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); CertPath certPath = certificateFactory.generateCertPath(certs); Certificate certificate = certPath.getCertificates().get(0); checkArgument(certificate instanceof X509Certificate); byte[] derData = certificate.getEncoded(); String deviceIdFromCertificate = derDataToDeviceIdString(derData); logger.trace("remote pem certificate =\n{}", derToPem(derData)); checkArgument(equal(deviceIdFromCertificate, deviceId), "device id mismatch! expected = %s, got = %s", deviceId, deviceIdFromCertificate); logger.debug("remote ssl certificate match deviceId = {}", deviceId); }
From source file:org.wso2.carbon.core.transports.util.CertProcessor.java
/** * Pump out the certificate//from www . j av a 2 s . com * * @param certificate cert * @param response response * @param outputStream out stream * @param serviceName service name * @throws AxisFault will be thrown */ private void serializeCert(Certificate certificate, CarbonHttpResponse response, OutputStream outputStream, String serviceName) throws AxisFault { try { response.addHeader(HTTP.CONTENT_TYPE, "application/octet-stream"); response.addHeader("Content-Disposition", "filename=" + serviceName + ".cert"); outputStream.write(certificate.getEncoded()); } catch (CertificateEncodingException e) { String msg = "Could not get encoded format of certificate"; log.error(msg, e); throw new AxisFault(msg, e); } catch (IOException e) { String msg = "Faliour when serializing to stream"; log.error(msg, e); throw new AxisFault(msg, e); } finally { try { outputStream.flush(); } catch (IOException e) { String msg = "Faliour when serializing to stream"; log.error(msg, e); } } }
From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java
public BrowserPOSTResponse handleResponse(SignatureStatus signatureStatus, byte[] signedDocument, String artifact, X509Certificate signerCertificate, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("handleResponse"); String target = retrieveTarget(httpSession); BrowserPOSTResponse browserPOSTResponse = new BrowserPOSTResponse(target); browserPOSTResponse.addAttribute("SignatureStatus", signatureStatus.getStatus()); /*//w w w. j a v a 2 s . com * Add RelayState if available */ String relayState = retrieveRelayState(httpSession); if (null != relayState) { browserPOSTResponse.addAttribute("RelayState", relayState); } if (SignatureStatus.OK == signatureStatus) { String signatureRequest = retrieveSignatureRequest(httpSession); String signatureRequestId = retrieveSignatureRequestId(httpSession); String encodedSignedDocument = Base64.encodeBase64String(signedDocument); if (null != signatureRequest) { browserPOSTResponse.addAttribute("SignatureResponse", encodedSignedDocument); } else { browserPOSTResponse.addAttribute("SignatureResponseId", artifact); } byte[] derSignerCertificate = signerCertificate.getEncoded(); String encodedSignatureCertificate = Base64.encodeBase64String(derSignerCertificate); browserPOSTResponse.addAttribute("SignatureCertificate", encodedSignatureCertificate); KeyStore.PrivateKeyEntry identityPrivateKeyEntry = this.dssContext.getIdentity(); if (null != identityPrivateKeyEntry) { LOG.debug("signing the response"); if (null != signatureRequest) { browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode( "target,SignatureRequest," + "SignatureResponse," + "SignatureCertificate", "UTF-8")); } else { browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode( "target,SignatureRequestId," + "SignatureResponseId," + "SignatureCertificate", "UTF-8")); } // service signature Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initSign(identityPrivateKeyEntry.getPrivateKey()); serviceSignature.update(target.getBytes()); if (null != signatureRequest) { serviceSignature.update(signatureRequest.getBytes()); serviceSignature.update(encodedSignedDocument.getBytes()); } else { serviceSignature.update(signatureRequestId.getBytes()); serviceSignature.update(artifact.getBytes()); } serviceSignature.update(encodedSignatureCertificate.getBytes()); byte[] serviceSignatureValue = serviceSignature.sign(); String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue); browserPOSTResponse.addAttribute("ServiceSignature", encodedServiceSignature); // service certificate chain Certificate[] serviceCertificateChain = identityPrivateKeyEntry.getCertificateChain(); browserPOSTResponse.addAttribute("ServiceCertificateChainSize", Integer.toString(serviceCertificateChain.length)); for (int certIdx = 0; certIdx < serviceCertificateChain.length; certIdx++) { Certificate certificate = serviceCertificateChain[certIdx]; String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded()); browserPOSTResponse.addAttribute("ServiceCertificate." + (certIdx + 1), encodedServiceCertificate); } } } return browserPOSTResponse; }