List of usage examples for java.security.cert CertificateFactory generateCertificate
public final Certificate generateCertificate(InputStream inStream) throws CertificateException
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Encrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding * Asymmetric encryption, with private and public key * * @param string String to encrypt// www. j a va2 s . com * @param cert contains public key in it * @return encrypted string */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static String encryptStringAsymmetric(String string, String cert) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException, CertificateException { Cipher cipher = Cipher.getInstance(RSA_CIPHER); String trimmedCert = cert.replace("-----BEGIN CERTIFICATE-----\n", "") .replace("-----END CERTIFICATE-----\n", ""); byte[] encodedCert = trimmedCert.getBytes("UTF-8"); byte[] decodedCert = org.apache.commons.codec.binary.Base64.decodeBase64(encodedCert); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(decodedCert); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(in); PublicKey realPublicKey = certificate.getPublicKey(); cipher.init(Cipher.ENCRYPT_MODE, realPublicKey); byte[] bytes = encodeStringToBase64Bytes(string); byte[] cryptedBytes = cipher.doFinal(bytes); return encodeBytesToBase64String(cryptedBytes); }
From source file:edu.vt.middleware.crypt.util.CryptReader.java
/** * Reads a certificate chain of the default certificate type from an input * stream containing data in any of the following formats: * * <ul>//from w ww .j ava 2 s .co m * <li>Sequence of DER-encoded certificates</li> * <li>Concatenation of PEM-encoded certificates</li> * <li>PKCS#7 certificate chain</li> * </ul> * * @param chainStream Stream containing certificate chain data. * @param type Type of certificate to read, e.g. X.509. * * @return Array of certificates in the order in which they appear in the * stream. * * @throws CryptException On certificate read or format errors. */ public static Certificate[] readCertificateChain(final InputStream chainStream, final String type) throws CryptException { final CertificateFactory cf = CryptProvider.getCertificateFactory(type); InputStream in = chainStream; if (!chainStream.markSupported()) { in = new BufferedInputStream(chainStream); } final List<Certificate> certList = new ArrayList<Certificate>(); try { while (in.available() > 0) { final Certificate cert = cf.generateCertificate(in); if (cert != null) { certList.add(cert); } } } catch (CertificateException e) { throw new CryptException("Certificate read/format error.", e); } catch (IOException e) { throw new CryptException("Stream I/O error."); } return certList.toArray(new Certificate[certList.size()]); }
From source file:test.integ.be.fedict.trust.util.TestUtils.java
public static List<X509Certificate> getNationalRegistryCertificateChain() throws Exception { Messages messages = new Messages(Locale.getDefault()); View view = new LogTestView(LOG); PcscEid pcscEid = new PcscEid(view, messages); if (!pcscEid.isEidPresent()) { LOG.debug("insert eID card..."); pcscEid.waitForEidPresent();//from ww w . j av a 2s . c o m } CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<X509Certificate> nrCertificateChain = new LinkedList<X509Certificate>(); try { byte[] nrCertData = pcscEid.readFile(PcscEid.RRN_CERT_FILE_ID); X509Certificate nrCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(nrCertData)); nrCertificateChain.add(nrCert); LOG.debug("national registry certificate issuer: " + nrCert.getIssuerX500Principal()); byte[] rootCaCertData = pcscEid.readFile(PcscEid.ROOT_CERT_FILE_ID); X509Certificate rootCaCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(rootCaCertData)); nrCertificateChain.add(rootCaCert); } finally { pcscEid.close(); } return nrCertificateChain; }
From source file:test.integ.be.e_contract.sts.CXFSTSClientTest.java
private static X509Certificate getCertificate(PrivateKey privateKey, PublicKey publicKey) throws Exception { X500Name subjectName = new X500Name("CN=Test"); X500Name issuerName = subjectName; // self-signed BigInteger serial = new BigInteger(128, new SecureRandom()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial, notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(privateKey.getEncoded()); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(asymmetricKeyParameter); X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); byte[] encodedCertificate = x509CertificateHolder.getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(encodedCertificate)); return certificate; }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }/*w w w .jav a 2 s. c o m*/ }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }
From source file:com.gamesalutes.utils.EncryptUtils.java
/** * Reads a DER-encoded certificate that uses binary or Base64 encoding from the given input stream. * //from ww w. ja v a 2 s . co m * @param in the <code>InputStream</code> * @param certType * @return the read certificate * @throws CertificateException * @throws IOException */ public static java.security.cert.Certificate readCertificate(InputStream in, String certType) throws CertificateException, IOException { // get the raw certificate bytes so that can trim and format cert properly byte[] data = null; try { data = ByteUtils.readBytes(in); // in automatically closed during call to readBytes even in case of exceptions in = null; } catch (Exception e) { in = null; throw new ChainedIOException("Error getting stream bytes", e); } CertificateFactory cf = CertificateFactory.getInstance(certType); try { byte[] pemData = formatBase64ToPem(getRawBase64Key(data), BEGIN_CERTIFICATE, END_CERTIFICATE); in = new ByteArrayInputStream(pemData); return cf.generateCertificate(in); } catch (Exception e) { MiscUtils.closeStream(in); // maybe it was in binary DER and couldn't be read when it was assumed to be in Base64 in = new ByteArrayInputStream(data); return cf.generateCertificate(in); } finally { MiscUtils.closeStream(in); } }
From source file:test.integ.be.fedict.performance.TestPKI.java
private static void loadCa(HttpClient httpClient, String testPkiPath, CAConfiguration ca) throws Exception { LOG.debug("load CA: " + ca.getName()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // load certificate URI certificateURI = new URI(testPkiPath + "/" + CertificateServlet.PATH + "?" + CertificateServlet.CA_QUERY_PARAM + "=" + ca.getName(), false); LOG.debug("URI: " + certificateURI.toString()); GetMethod getMethod = new GetMethod(certificateURI.toString()); httpClient.executeMethod(getMethod); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(getMethod.getResponseBodyAsStream()); ca.setCertificate(certificate);//from ww w .ja v a2 s . c om // load private key URI keyURI = new URI(testPkiPath + "/" + PrivateKeyServlet.PATH + "?" + PrivateKeyServlet.CA_QUERY_PARAM + "=" + ca.getName(), false); getMethod = new GetMethod(keyURI.toString()); httpClient.executeMethod(getMethod); PEMReader pemReader = new PEMReader(new InputStreamReader(getMethod.getResponseBodyAsStream())); KeyPair keyPair = (KeyPair) pemReader.readObject(); ca.setKeyPair(keyPair); }
From source file:com.google.android.gms.common.GooglePlayServicesUtil.java
private static byte[] m107a(PackageInfo packageInfo, byte[]... bArr) { try {// ww w . j a va 2s. com CertificateFactory instance = CertificateFactory.getInstance("X509"); if (packageInfo.signatures.length != 1) { Log.w("GooglePlayServicesUtil", "Package has more than one signature."); return null; } try { try { ((X509Certificate) instance .generateCertificate(new ByteArrayInputStream(packageInfo.signatures[0].toByteArray()))) .checkValidity(); byte[] toByteArray = packageInfo.signatures[0].toByteArray(); for (byte[] bArr2 : bArr) { if (Arrays.equals(bArr2, toByteArray)) { return bArr2; } } if (Log.isLoggable("GooglePlayServicesUtil", 2)) { Log.v("GooglePlayServicesUtil", "Signature not valid. Found: \n" + Base64.encodeToString(toByteArray, 0)); } return null; } catch (CertificateExpiredException e) { Log.w("GooglePlayServicesUtil", "Certificate has expired."); return null; } catch (CertificateNotYetValidException e2) { Log.w("GooglePlayServicesUtil", "Certificate is not yet valid."); return null; } } catch (CertificateException e3) { Log.w("GooglePlayServicesUtil", "Could not generate certificate."); return null; } } catch (CertificateException e4) { Log.w("GooglePlayServicesUtil", "Could not get certificate instance."); return null; } }
From source file:org.apache.jmeter.assertions.SMIMEAssertion.java
private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s, String name) throws CMSException { AssertionResult res = new AssertionResult(name); try {/*from w w w. ja v a2 s .com*/ Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Iterator<?> signerIt = signers.getSigners().iterator(); if (signerIt.hasNext()) { SignerInformation signer = (SignerInformation) signerIt.next(); Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator(); if (certIt.hasNext()) { // the signer certificate X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); if (testElement.isVerifySignature()) { SignerInformationVerifier verifier = null; try { verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert); } catch (OperatorCreationException e) { log.error("Can't create a provider", e); } if (verifier == null || !signer.verify(verifier)) { res.setFailure(true); res.setFailureMessage("Signature is invalid"); } } if (testElement.isSignerCheckConstraints()) { StringBuilder failureMessage = new StringBuilder(); String serial = testElement.getSignerSerial(); if (!JOrphanUtils.isBlank(serial)) { BigInteger serialNbr = readSerialNumber(serial); if (!serialNbr.equals(cert.getSerialNumber())) { res.setFailure(true); failureMessage.append("Serial number ").append(serialNbr) .append(" does not match serial from signer certificate: ") .append(cert.getSerialNumber()).append("\n"); } } String email = testElement.getSignerEmail(); if (!JOrphanUtils.isBlank(email)) { List<String> emailFromCert = getEmailFromCert(cert); if (!emailFromCert.contains(email)) { res.setFailure(true); failureMessage.append("Email address \"").append(email) .append("\" not present in signer certificate\n"); } } String subject = testElement.getSignerDn(); if (subject.length() > 0) { final X500Name certPrincipal = cert.getSubject(); log.debug("DN from cert: " + certPrincipal.toString()); X500Name principal = new X500Name(subject); log.debug("DN from assertion: " + principal.toString()); if (!principal.equals(certPrincipal)) { res.setFailure(true); failureMessage.append("Distinguished name of signer certificate does not match \"") .append(subject).append("\"\n"); } } String issuer = testElement.getIssuerDn(); if (issuer.length() > 0) { final X500Name issuerX500Name = cert.getIssuer(); log.debug("IssuerDN from cert: " + issuerX500Name.toString()); X500Name principal = new X500Name(issuer); log.debug("IssuerDN from assertion: " + principal); if (!principal.equals(issuerX500Name)) { res.setFailure(true); failureMessage .append("Issuer distinguished name of signer certificate does not match \"") .append(subject).append("\"\n"); } } if (failureMessage.length() > 0) { res.setFailureMessage(failureMessage.toString()); } } if (testElement.isSignerCheckByFile()) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CertificateHolder certFromFile; InputStream inStream = null; try { inStream = new BufferedInputStream( new FileInputStream(testElement.getSignerCertFile())); certFromFile = new JcaX509CertificateHolder( (X509Certificate) cf.generateCertificate(inStream)); } finally { IOUtils.closeQuietly(inStream); } if (!certFromFile.equals(cert)) { res.setFailure(true); res.setFailureMessage("Signer certificate does not match certificate " + testElement.getSignerCertFile()); } } } else { res.setFailure(true); res.setFailureMessage("No signer certificate found in signature"); } } // TODO support multiple signers if (signerIt.hasNext()) { log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported."); } } catch (GeneralSecurityException e) { log.error(e.getMessage(), e); res.setError(true); res.setFailureMessage(e.getMessage()); } catch (FileNotFoundException e) { res.setFailure(true); res.setFailureMessage("certificate file not found: " + e.getMessage()); } return res; }
From source file:org.kse.crypto.x509.X509CertUtil.java
/** * Convert the supplied certificate object into an X509Certificate object. * * @param certIn//from ww w .j a v a2 s. c o m * The Certificate object * @return The converted X509Certificate object * @throws CryptoException * A problem occurred during the conversion */ public static X509Certificate convertCertificate(Certificate certIn) throws CryptoException { try { CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); ByteArrayInputStream bais = new ByteArrayInputStream(certIn.getEncoded()); return (X509Certificate) cf.generateCertificate(bais); } catch (CertificateException | NoSuchProviderException e) { throw new CryptoException(res.getString("NoConvertCertificate.exception.message"), e); } }