List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:learn.encryption.ssl.SSLContext_Https.java
public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) { if (sslContext != null) { return sslContext; }/*from ww w . j a v a 2 s . com*/ try { // ??, ??assets //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer"); InputStream inputStream = new FileInputStream(new File(servercerfile)); // ?? CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); Certificate cer = cerFactory.generateCertificate(inputStream); // ?KeyStore KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12?? keyStore.load(null, null); keyStore.setCertificateEntry("trust", cer); // KeyStoreTrustManagerFactory TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext = SSLContext.getInstance("TLS"); //?clientKeyStore(android??bks) //KeyStore clientKeyStore = KeyStore.getInstance("BKS"); KeyStore clientKeyStore = KeyStore.getInstance("jks"); //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray()); clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray()); // ?clientKeyStorekeyManagerFactory KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, clientPass.toCharArray()); // ?SSLContext trustManagerFactory.getTrustManagers() sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());//new TrustManager[]{trustManagers}?? } catch (Exception e) { e.printStackTrace(); } return sslContext; }
From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java
@SuppressWarnings("static-access") private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert) throws JAXRException { Certificate[] certChain = new Certificate[2]; try {/*from ww w .j a v a 2 s. co m*/ // Save cert in a temporary keystore file which is sent as // repository item to server so it can be signed KeyStore tmpKeystore = KeyStore.getInstance("JKS"); tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert); File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks"); repositoryItemFile.deleteOnExit(); FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile); tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); fos.flush(); fos.close(); // Now have server sign the cert using extensionRequest javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile)); String id = it.cnr.icar.eric.common.Utility.getInstance().createId(); HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>(); idToRepositoryItemsMap.put(id, repositoryItem); HashMap<String, String> slotsMap = new HashMap<String, String>(); slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true"); RegistryRequestType req = bu.rsFac.createRegistryRequestType(); bu.addSlotsToRequest(req, slotsMap); RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req, idToRepositoryItemsMap); DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id); InputStream is = responseRepositoryItem.getInputStream(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray()); is.close(); certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP); if (certChain[0] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert")); } certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS); if (certChain[1] == null) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert")); } } catch (Exception e) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e); } return certChain; }
From source file:learn.encryption.ssl.SSLContext_Https.java
/** * @description javaSSLContext/*w ww. ja va 2s . com*/ * @description https?, SSLContext (NoHttp?SecureRandombug) * @description client.ks?server * @description ?? * @description ????getSSLContext2() */ //@SuppressLint("TrulyRandom") public static SSLContext getSSLContext() { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); // ??, ??assets InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks")); //App.getInstance().getAssets().open("srca.cer"); // ?? CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); // ?KeyStore KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(inputStream, "123456".toCharArray()); //Certificate cer = cerFactory.generateCertificate(inputStream); Certificate cer = keyStore.getCertificate("clientKey"); keyStore.setCertificateEntry("trust", cer); // KeyStorekeyManagerFactory KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "123456".toCharArray()); // KeyStoreTrustManagerFactory TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); // ?SSLContext sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); } catch (Exception e) { e.printStackTrace(); } return sslContext; }
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;/* www . j a va2 s . c o m*/ String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:Main.java
private static TrustManager[] prepareTrustManager(InputStream... certificates) { if (certificates != null && certificates.length > 0) { try {//from w w w. j a v a2s .c om CertificateFactory e = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load((KeyStore.LoadStoreParameter) null); int index = 0; InputStream[] trustManagerFactory = certificates; int trustManagers = certificates.length; for (int i$ = 0; i$ < trustManagers; ++i$) { InputStream certificate = trustManagerFactory[i$]; String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, e.generateCertificate(certificate)); try { if (certificate != null) { certificate.close(); } } catch (IOException var10) { ; } } trustManagerFactory = null; TrustManagerFactory var15 = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); var15.init(keyStore); TrustManager[] var16 = var15.getTrustManagers(); return var16; } catch (NoSuchAlgorithmException var11) { var11.printStackTrace(); } catch (CertificateException var12) { var12.printStackTrace(); } catch (KeyStoreException var13) { var13.printStackTrace(); } catch (Exception var14) { var14.printStackTrace(); } return null; } else { return null; } }
From source file:nl.surfnet.spring.security.opensaml.util.KeyStoreUtil.java
/** * Append a certificate to the given key store * @param keyStore//from ww w.j a v a2s. c o m * @param keyAlias * @param pemCert */ public static void appendCertificateToKeyStore(KeyStore keyStore, String keyAlias, String pemCert) { String wrappedCert = "-----BEGIN CERTIFICATE-----\n" + pemCert + "\n-----END CERTIFICATE-----"; ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(wrappedCert.getBytes()); try { final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); final Certificate cert = certificateFactory.generateCertificate(certificateInputStream); IOUtils.closeQuietly(certificateInputStream); keyStore.setCertificateEntry(keyAlias, cert); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Copies certificates from one keystore to another (both keystore has to be * initialized./*from w w w . jav a2 s . co m*/ * * @param fromKeyStore * @param toKeyStore * @return */ public static boolean copyCertificates(KeyStore fromKeyStore, KeyStore toKeyStore) { if (fromKeyStore == null || toKeyStore == null) { return false; } try { for (String alias : getCertAliases(fromKeyStore)) { toKeyStore.setCertificateEntry(alias, fromKeyStore.getCertificate(alias)); } return true; } catch (KeyStoreException e) { e.printStackTrace(); } return false; }
From source file:com.aware.ui.Plugins_Manager.java
/** * Downloads and compresses image for optimized icon caching * @param image_url/*ww w . j av a2s . c om*/ * @return */ public static byte[] cacheImage(String image_url, Context sContext) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = sContext.getResources().openRawResource(R.raw.aware); Certificate ca; try { ca = cf.generateCertificate(caInput); } finally { caInput.close(); } KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework); sKeyStore.load(inStream, "awareframework".toCharArray()); inStream.close(); sKeyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(sKeyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); //Fetch image now that we recognise SSL URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection(); image_connection.setSSLSocketFactory(context.getSocketFactory()); InputStream in_stream = image_connection.getInputStream(); Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream); ByteArrayOutputStream output = new ByteArrayOutputStream(); tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output); return output.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; }
From source file:com.iaspec.rda.plugins.rfid.license.LicenseReader.java
public static void verifyChallengeCode(String challenge, String expect, Device device) throws RdaException { ChallengeVerifier verifier = ChallengeVerifier.getInstance(); byte[] pkcs7 = Base64.decode(challenge); SignatureVerificationResultHolder resultHolder = null; try {//from w w w . ja v a2 s .co m resultHolder = verifier.verifySignature(pkcs7); } catch (SignatureInvalidException se) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } catch (CryptoException se) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } CertificateDnInfoDTO certSubjectDn = CertUtil.getCertificateSubjectInfo(resultHolder.signingCertChain[0]); // Handle CN checks String cn = certSubjectDn.getCn().get(0).toString(); if (!cn.equalsIgnoreCase(device.getId())) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE); } logger.debug("Signature Verification success: certSubject=[" + resultHolder.signingCertChain[0].getSubjectDN().toString() + "], orignialContent=[" + new String(resultHolder.originalData) + "]"); if (!new String(resultHolder.originalData).equalsIgnoreCase(expect)) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } try { KeyStore trustedStore = KeyStore.getInstance("JKS"); trustedStore.load(null, null); // byte[] certBytes = IOUtils.toByteArray(new // FileInputStream("RDA_RFID_CA_2.cer")); //false CA certificate // byte[] certBytes = IOUtils.toByteArray(new // FileInputStream("RDA_RFID_CA.cer")); byte[] certBytes = IOUtils.toByteArray(ResourceHelper.readResource("RDA_RFID_CA.cer")); // valid CA certificate X509Certificate cert = CertUtil.getX509Certificate(certBytes); // may add any trusted certificate (CA or Self-signed) to the // keystore... trustedStore.setCertificateEntry(cert.getSubjectDN().getName().toString(), cert); verifier.isCertificateTrust(resultHolder.signingCertChain[0], trustedStore, null); // if trusted, do CRL verification if crl can supplied /* * if * (!CertUtil.verifyRevoked(ResourceHelper.readResource("crl.crl"), * cert)) { throw new * RdaException(ExceptionMessages.EXCEPTION_CERTIFICATE_IS_REVOKED); * } */ } catch (com.iaspec.rda.rfid.server.crypto.exception.CertificateNotValidException se) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE); } catch (CertificateException ce) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } catch (RdaException e) { throw new RdaException(e.getMessage()); } catch (Exception e) { throw new RdaException(ExceptionMessages.EXCEPTION_SYSTEM); } logger.debug("The certificate is trusted"); }
From source file:org.panlab.tgw.restclient.PtmInfoParser.java
private static void processCertificate(String alias, X509Certificate x509, URL url) { try {/* w ww .j av a 2s.c o m*/ String store = System.getProperty("javax.net.ssl.trustStore"); String password = System.getProperty("javax.net.ssl.trustStorePassword"); KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(new FileInputStream(store), password.toCharArray()); Enumeration<String> en = keystore.aliases(); while (en.hasMoreElements()) { log.info(en.nextElement()); } if (!keystore.containsAlias(alias)) { ByteArrayInputStream bais = new ByteArrayInputStream(x509.getEncoded()); Certificate cert = CertificateFactory.getInstance("x509").generateCertificate(bais); keystore.setCertificateEntry(alias, cert); storeNewPTM(alias, url, x509.getSubjectDN().toString().replace(", ", ",")); en = keystore.aliases(); while (en.hasMoreElements()) { log.info(en.nextElement()); } keystore.store(new FileOutputStream(store), password.toCharArray()); TrustManagerFactory.getInstance("PKIX").init(keystore); } } catch (Exception error) { log.error(error.getMessage()); } }