private SSLSocketFactory createSslSocketFactory() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { // load up the key store String STORETYPE = "JKS"; String KEYSTORE = "keystore.jks"; String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance(STORETYPE); ks.load(MattermostClient.class.getResourceAsStream(KEYSTORE), STOREPASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, KEYPASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = null; sslContext = SSLContext.getInstance("TLS"); // sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); sslContext.init(null, null, null); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates return sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault(); }
@SuppressWarnings("deprecation") static CloseableHttpClient buildClient(boolean ignoreSSL) throws Exception { SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted( final X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy... return true; } }); if (ignoreSSL) { return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { return HttpClients.createDefault(); } }
/** * Create the named SignatureFileVerifier. * * @param name the name of the signature block file (.DSA/.RSA/.EC) * * @param rawBytes the raw bytes of the signature block file */ public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache, ManifestDigester md, String name, byte rawBytes[]) throws IOException, CertificateException { // new PKCS7() calls CertificateFactory.getInstance() // need to use local providers here, see Providers class Object obj = null; try { obj = Providers.startJarVerification(); block = new PKCS7(rawBytes); sfBytes = block.getContentInfo().getData(); certificateFactory = CertificateFactory.getInstance("X509"); } finally { Providers.stopJarVerification(obj); } this.name = name.substring(0, name.lastIndexOf(".")) .toUpperCase(Locale.ENGLISH); this.md = md; this.signerCache = signerCache; }
private static X509Certificate createX509CertificateFromFile( final String certificateFileName) throws IOException, CertificateException { // Load an X509 certificate from the specified certificate file name final File file = new java.io.File(certificateFileName); if (!file.isFile()) { throw new IOException( String.format("The certificate file %s doesn't exist.", certificateFileName)); } final CertificateFactory certificateFactoryX509 = CertificateFactory.getInstance("X.509"); final InputStream inputStream = new FileInputStream(file); final X509Certificate certificate = (X509Certificate) certificateFactoryX509.generateCertificate(inputStream); inputStream.close(); return certificate; }
/** * Retrieves all certs from the specified CertStores that satisfy the * requirements specified in the parameters and the current * PKIX state (name constraints, policy constraints, etc). * * @param currentState the current state. * Must be an instance of <code>ReverseState</code> * @param certStores list of CertStores */ @Override Collection<X509Certificate> getMatchingCerts (State currState, List<CertStore> certStores) throws CertStoreException, CertificateException, IOException { ReverseState currentState = (ReverseState) currState; if (debug != null) debug.println("In ReverseBuilder.getMatchingCerts."); /* * The last certificate could be an EE or a CA certificate * (we may be building a partial certification path or * establishing trust in a CA). * * Try the EE certs before the CA certs. It will be more * common to build a path to an end entity. */ Collection<X509Certificate> certs = getMatchingEECerts(currentState, certStores); certs.addAll(getMatchingCACerts(currentState, certStores)); return certs; }
/** * Construct a {@code LocalOcspRequest} from its DER encoding. * * @param requestBytes the DER-encoded bytes * * @throws IOException if decoding errors occur * @throws CertificateException if certificates are found in the * OCSP request and they do not parse correctly. */ private LocalOcspRequest(byte[] requestBytes) throws IOException, CertificateException { Objects.requireNonNull(requestBytes, "Received null input"); DerInputStream dis = new DerInputStream(requestBytes); // Parse the top-level structure, it should have no more than // two elements. DerValue[] topStructs = dis.getSequence(2); for (DerValue dv : topStructs) { if (dv.tag == DerValue.tag_Sequence) { parseTbsRequest(dv); } else if (dv.isContextSpecific((byte)0)) { parseSignature(dv); } else { throw new IOException("Unknown tag at top level: " + dv.tag); } } }
private String getCertificateThumbprint(String pfxPath, String password) { try { InputStream inStream = new FileInputStream(pfxPath); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(inStream, password.toCharArray()); String alias = ks.aliases().nextElement(); X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); inStream.close(); MessageDigest sha = MessageDigest.getInstance("SHA-1"); return BaseEncoding.base16().encode(sha.digest(certificate.getEncoded())); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException ex) { throw new RuntimeException(ex); } }
/** * Set the attribute value. * @exception CertificateException on attribute handling errors. */ public void set(String name, Object obj) throws CertificateException, IOException { if (!(obj instanceof Date)) { throw new CertificateException("Attribute must be of type Date."); } if (name.equalsIgnoreCase(NOT_BEFORE)) { notBefore = (Date)obj; } else if (name.equalsIgnoreCase(NOT_AFTER)) { notAfter = (Date)obj; } else { throw new CertificateException("Attribute name not recognized by" + " CertAttrSet:PrivateKeyUsage."); } encodeThis(); }
private String getKeyFromConfigServer(RestTemplate keyUriRestTemplate) throws CertificateException { // Load available UAA servers discoveryClient.getServices(); HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders()); String content = keyUriRestTemplate .exchange("http://config/api/token_key", HttpMethod.GET, request, String.class).getBody(); if (StringUtils.isBlank(content)) { throw new CertificateException("Received empty certificate from config."); } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance(Constants.CERTIFICATE); X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return String.format(Constants.PUBLIC_KEY, new String(Base64.encode(pk.getEncoded()))); }
/** * Checks if a certificate is untrusted. * * @param cert the certificate to check * @return true if the certificate is untrusted. */ public static boolean isUntrusted(X509Certificate cert) { if (algorithm == null) { return false; } String key; if (cert instanceof X509CertImpl) { key = ((X509CertImpl)cert).getFingerprint(algorithm); } else { try { key = new X509CertImpl(cert.getEncoded()).getFingerprint(algorithm); } catch (CertificateException cee) { return false; } } return props.containsKey(key); }
public static void main(String[] args) throws Exception { List certs = new Vector(); certs.add("The 1st certificate"); certs.add("The 2nd certificate"); certs.add("The 3rd certificate"); certs.add("The 4th certificate"); try { X509CertPath cp = new X509CertPath(certs); throw new Exception("No expected CertificateException thrown"); } catch (CertificateException ce) { // get the expected exception } catch (Exception e) { throw new Exception("No expected CertificateException thrown", e); } }
private X509Certificate loadCert(Session session, long oHandle) throws PKCS11Exception, CertificateException { CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_VALUE) }; token.p11.C_GetAttributeValue(session.id(), oHandle, attrs); byte[] bytes = attrs[0].getByteArray(); if (bytes == null) { throw new CertificateException ("unexpectedly retrieved null byte array"); } CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate)cf.generateCertificate (new ByteArrayInputStream(bytes)); }
private void testPrivateKeyValid() throws IOException, CertificateException { System.out.println("X.509 Certificate Match on privateKeyValid"); // bad match X509CertSelector selector = new X509CertSelector(); Calendar cal = Calendar.getInstance(); cal.set(1968, 12, 31); selector.setPrivateKeyValid(cal.getTime()); checkMatch(selector, cert, false); // good match DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.16")); byte[] encoded = in.getOctetString(); PrivateKeyUsageExtension ext = new PrivateKeyUsageExtension(false, encoded); Date validDate = (Date) ext.get(PrivateKeyUsageExtension.NOT_BEFORE); selector.setPrivateKeyValid(validDate); checkMatch(selector, cert, true); }
/** * Retrieve provider metadata. * Provider configuration information * Obtaining the provider configuration information can be done either out-of-band or using the optional discovery process: * * @throws IOException Signals that an I/O exception has occurred. * @throws ParseException the parse exception * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public void retrieveProviderMetadata() throws IOException, ParseException, KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException { URL providerConfigurationURL = issuerURI.resolve(URLPATH_WELL_KNOWN_OPENID).toURL(); // System.out.println(providerConfigurationURL); URLConnection conn = providerConfigurationURL.openConnection(); if (trustStoreFile != null) { Trust.trustSpecific((HttpsURLConnection) conn, trustStoreFile); } InputStream stream = conn.getInputStream(); // Read all data from URL String providerInfo = null; try (java.util.Scanner s = new java.util.Scanner(stream)) { providerInfo = s.useDelimiter("\\A").hasNext() ? s.next() : ""; } setProviderMetadata(OIDCProviderMetadata.parse(providerInfo)); }
public PublicKey getPublicKey(String keyName) throws CryptoException { PublicKey publicKey = null; try { KeyStore mKeyStore = KeyStore.getInstance(REST_AUTH_KEYSTORE_NAME); mKeyStore.load(null); Certificate certificate = mKeyStore.getCertificate(keyName); if (certificate != null) publicKey = certificate.getPublicKey(); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { throw new CryptoException(e.getMessage()); } return publicKey; }
/** * Connect to the authorization server and get a valid token. * * @param username the username * @param password the password * @return true, if successful * @throws IOException * @throws URISyntaxException * @throws ParseException * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public boolean authorizeByUserAndPW(String username, String password) throws URISyntaxException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException { String authRedirection = ""; if (!inited) { this.init(); } oidcClient.setResourceOwnerCredentials(username, password); oidcClient.requestToken(); urlProcessor.setAccessToken(oidcClient.getAccessToken()); authRedirection = urlProcessor.prepare(oidcClient.getRedirectURI().toURL()).process(); if (authRedirection == null) { // authenticated lastSuccessfulUser = username; if (availabilityHandler != null) { availabilityHandler.onResourceAvailable(urlProcessor); } return true; } else { System.err.println("OIDC authorization failed"); System.err.println("authRedirection=" + authRedirection); return false; } }
private KeyStore getKeyStore(Resource resource, String password) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { try (InputStream stream = resource.getInputStream()) { KeyStore keyStore; String filename = resource.getFilename().toLowerCase(); if (filename.endsWith("pfx") || filename.endsWith("p12")) { keyStore = KeyStore.getInstance("PKCS12"); } else { keyStore = KeyStore.getInstance("JKS"); } keyStore.load(stream,password.toCharArray()); return keyStore; } }
@Override public TlsAuthentication getAuthentication() throws IOException { return new TlsAuthentication() { @Override public void notifyServerCertificate(Certificate serverCertificate) throws IOException { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List<java.security.cert.Certificate> certs = new LinkedList<java.security.cert.Certificate>(); for (org.bouncycastle.asn1.x509.Certificate c : serverCertificate.getCertificateList()) { certs.add(cf.generateCertificate(new ByteArrayInputStream(c.getEncoded()))); } peertCerts = certs.toArray(new java.security.cert.Certificate[0]); } catch (CertificateException e) { System.out.println("Failed to cache server certs" + e); throw new IOException(e); } } @Override public TlsCredentials getClientCredentials(CertificateRequest arg0) throws IOException { return null; } }; }
/** * Add a new certificate for the incoming or outgoing server to the local key store. */ public void addCertificate(CheckDirection direction, X509Certificate certificate) throws CertificateException { Uri uri; if (direction == CheckDirection.INCOMING) { uri = Uri.parse(getStoreUri()); } else { uri = Uri.parse(getTransportUri()); } LocalKeyStore localKeyStore = LocalKeyStore.getInstance(); localKeyStore.addCertificate(uri.getHost(), uri.getPort(), certificate); }
public synchronized void addCertificate(String host, int port, X509Certificate certificate) throws CertificateException { if (mKeyStore == null) { throw new CertificateException( "Certificate not added because key store not initialized"); } try { mKeyStore.setCertificateEntry(getCertKey(host, port), certificate); } catch (KeyStoreException e) { throw new CertificateException( "Failed to add certificate to local key store", e); } writeCertificateFile(); }
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { localTrustManager.checkServerTrusted(chain, authType); } }
@Override public void checkServerTrusted(final X509Certificate[] x509Certificates, final String s, final SSLEngine sslEngine) throws CertificateException { with(new Consumer() { @Override public void accept(X509ExtendedTrustManager delegate) throws CertificateException { delegate.checkServerTrusted(x509Certificates, s, sslEngine); } }); }
public static String v(Context context) { PackageInfo packageInfo; String str = null; try { packageInfo = context.getPackageManager().getPackageInfo(u(context), 64); } catch (NameNotFoundException e) { e.printStackTrace(); Object obj = str; } InputStream byteArrayInputStream = new ByteArrayInputStream(packageInfo.signatures[0].toByteArray()); try { CertificateFactory instance = CertificateFactory.getInstance("X509"); } catch (CertificateException e2) { e2.printStackTrace(); obj = str; } try { X509Certificate x509Certificate = (X509Certificate) instance.generateCertificate(byteArrayInputStream); } catch (CertificateException e22) { e22.printStackTrace(); obj = str; } try { str = a(MessageDigest.getInstance(CommonUtils.MD5_INSTANCE).digest(x509Certificate.getEncoded())); } catch (NoSuchAlgorithmException e3) { e3.printStackTrace(); } catch (CertificateEncodingException e4) { e4.printStackTrace(); } return str; }
public X509Certificate parseCertificate(String pemBlock) throws IOException { PEMParser p2 = new PEMParser(new StringReader(cleanupPEM(pemBlock))); Object o2 = p2.readObject(); if (o2 == null) throw new InvalidParameterException("Could not read certificate. Expected the certificate to begin with '-----BEGIN CERTIFICATE-----'."); if (!(o2 instanceof X509CertificateHolder)) throw new InvalidParameterException("Expected X509CertificateHolder, got " + o2.getClass().getName()); JcaX509CertificateConverter certconv = new JcaX509CertificateConverter().setProvider("BC"); try { return certconv.getCertificate((X509CertificateHolder) o2); } catch (CertificateException e) { throw new IOException(e); } }
/** * Initialize trustStore with Spring set properties: * <ul> * <li>ldap.authentication.truststore.path * <li>ldap.authentication.truststore.type * <li>ldap.authentication.truststore.passphrase * </ul> * * @return {@link KeyStore} with loaded trustStore file */ private KeyStore initTrustStore() { KeyStore ks; String trustStoreType = getTrustStoreType(); try { ks = KeyStore.getInstance(trustStoreType); } catch (KeyStoreException kse) { throw new AlfrescoRuntimeException("No provider supports " + trustStoreType, kse); } try { ks.load(new FileInputStream(getTrustStorePath()), getTrustStorePassPhrase().toCharArray()); } catch (FileNotFoundException fnfe) { throw new AlfrescoRuntimeException("The truststore file is not found.", fnfe); } catch (IOException ioe) { throw new AlfrescoRuntimeException("The truststore file cannot be read.", ioe); } catch (NoSuchAlgorithmException nsae) { throw new AlfrescoRuntimeException("Algorithm used to check the integrity of the truststore cannot be found.", nsae); } catch (CertificateException ce) { throw new AlfrescoRuntimeException("The certificates cannot be loaded from truststore.", ce); } return ks; }
/** * @throws CertificateException if the certificate has expired or if the certificate is not yet valid. */ @Override public void validateCertificates(X509Certificate[] serverCertificates) throws CertificateException { for (X509Certificate certificate : serverCertificates) { certificate.checkValidity(); } }
/** * 获取SSLContext * @param trustPasswd * @param keyPasswd * @return * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static SSLContext getSSLContext( FileInputStream trustFileInputStream, String trustPasswd, FileInputStream keyFileInputStream, String keyPasswd) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { // ca TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509); KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS); trustKeyStore.load(trustFileInputStream, HttpClientUtil .str2CharArray(trustPasswd)); tmf.init(trustKeyStore); final char[] kp = HttpClientUtil.str2CharArray(keyPasswd); KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509); KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12); ks.load(keyFileInputStream, kp); kmf.init(ks, kp); SecureRandom rand = new SecureRandom(); SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand); return ctx; }
@SuppressLint({"StringFormatMatches", "StringFormatInvalid"}) private String getMobileInfoString(Context c) { c.getPackageManager(); String apksign = "error getting package signature"; String version = "error getting version"; try { @SuppressLint("PackageManagerGetSignatures") Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray())); MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = cert.getEncoded(); md.update(der); byte[] digest = md.digest(); if (Arrays.equals(digest, VpnStatus.officalkey)) apksign = c.getString(R.string.official_build); else if (Arrays.equals(digest, VpnStatus.officaldebugkey)) apksign = c.getString(R.string.debug_build); else if (Arrays.equals(digest, VpnStatus.amazonkey)) apksign = "amazon version"; else if (Arrays.equals(digest, VpnStatus.fdroidkey)) apksign = "F-Droid built and signed version"; else apksign = c.getString(R.string.built_by, cert.getSubjectX500Principal().getName()); PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); version = packageinfo.versionName; } catch (PackageManager.NameNotFoundException | CertificateException | NoSuchAlgorithmException ignored) { } Object[] argsext = Arrays.copyOf(mArgs, mArgs.length); argsext[argsext.length - 1] = apksign; argsext[argsext.length - 2] = version; return c.getString(R.string.mobile_info, argsext); }
@Override public void checkClientTrusted(final X509Certificate[] x509Certificates, final String s, final SSLEngine sslEngine) throws CertificateException { with(new Consumer() { @Override public void accept(X509ExtendedTrustManager delegate) throws CertificateException { delegate.checkClientTrusted(x509Certificates, s, sslEngine); } }); }
public static boolean verifyZip(Context context, String zipPath) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); InputStream in = context.getAssets().open("test.cer"); Certificate certificate = certificateFactory.generateCertificate(in); in.close(); return verifyZip(zipPath, certificate); } catch (IOException | CertificateException e) { e.printStackTrace(); return false; } }
@Test public void nonRetryableSSLHandshakeException() throws Exception { ConnectionSpecSelector connectionSpecSelector = createConnectionSpecSelector(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS); SSLSocket socket = createSocketWithEnabledProtocols(TlsVersion.TLS_1_1, TlsVersion.TLS_1_0); connectionSpecSelector.configureSecureSocket(socket); SSLHandshakeException trustIssueException = new SSLHandshakeException("Certificate handshake exception"); trustIssueException.initCause(new CertificateException()); boolean retry = connectionSpecSelector.connectionFailed(trustIssueException); assertFalse(retry); socket.close(); }
private String getKeyFromConfigServer(TokenKeyService tokenKeyService) throws CertificateException { String content = tokenKeyService.getKey(); if (StringUtils.isBlank(content)) { throw new CertificateException("Certificate not found."); } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance(CERTIFICATE); X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return String.format(PUBLIC_KEY, new String(Base64.encode(pk.getEncoded()))); }
/** * Return the Class object associated with this attribute. */ Class<?> getClazz() throws CertificateException { try { Class<?> c = clazz; if (c == null) { c = Class.forName(className); clazz = c; } return c; } catch (ClassNotFoundException e) { throw new CertificateException("Could not load class: " + e, e); } }
@Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { X509TrustManager tm = trustManagerRef.get(); if (tm != null) { tm.checkClientTrusted(chain, authType); } else { throw new CertificateException("Unknown client chain certificate: " + chain[0].toString()); } }
public static KeyStore loadKeyStore(String file, KeyStoreType type, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { KeyStore ks = KeyStore.getInstance(type.name()); try (FileInputStream fin = new FileInputStream(file)) { ks.load(fin, passwd); } return ks; }
public final void verify( PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); Signature signature = Signature.getInstance(sigName, sigProvider); checkSignature(key, signature); }
public void engineStore(OutputStream out, char[] passwd) throws IOException, NoSuchAlgorithmException, CertificateException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(charsToBytes(passwd)); md.update("Mighty Aphrodite".getBytes("UTF-8")); DataOutputStream dout = new DataOutputStream(new DigestOutputStream(out, md)); dout.writeInt(MAGIC); dout.writeInt(2); dout.writeInt(aliases.size()); for (Enumeration e = aliases.elements(); e.hasMoreElements(); ) { String alias = (String) e.nextElement(); if (trustedCerts.containsKey(alias)) { dout.writeInt(TRUSTED_CERT); dout.writeUTF(alias); dout.writeLong(((Date) dates.get(alias)).getTime()); writeCert(dout, (Certificate) trustedCerts.get(alias)); } else { dout.writeInt(PRIVATE_KEY); dout.writeUTF(alias); dout.writeLong(((Date) dates.get(alias)).getTime()); byte[] key = (byte[]) privateKeys.get(alias); dout.writeInt(key.length); dout.write(key); Certificate[] chain = (Certificate[]) certChains.get(alias); dout.writeInt(chain.length); for (int i = 0; i < chain.length; i++) writeCert(dout, chain[i]); } } byte[] digest = md.digest(); dout.write(digest); }
@Override public void addTlsKey(File pubCertFile) { log.info("Adding TLS key from {}", pubCertFile.getAbsolutePath()); try { CertificateFactory fact = CertificateFactory.getInstance("X.509"); FileInputStream is = new FileInputStream(pubCertFile); X509Certificate cer = (X509Certificate) fact.generateCertificate(is); String fingerprint = sha256.hash(cer.getEncoded()); log.info("Fingerprint: {}", fingerprint); tlsFingerprints.add(new TlsKey(fingerprint)); } catch (CertificateException | IOException e) { throw new RuntimeException(e); } }
/** * Try loading from the user specified path, else load from the backup * path in case Exception is not due to bad/wrong password * @param path Actual path to load from * @param backupPath Backup path (_OLD) * @return The permissions of the loaded file * @throws NoSuchAlgorithmException * @throws CertificateException * @throws IOException */ private FsPermission tryLoadFromPath(Path path, Path backupPath) throws NoSuchAlgorithmException, CertificateException, IOException { FsPermission perm = null; try { perm = loadFromPath(path, password); // Remove _OLD if exists if (fs.exists(backupPath)) { fs.delete(backupPath, true); } LOG.debug("KeyStore loaded successfully !!"); } catch (IOException ioe) { // If file is corrupted for some reason other than // wrong password try the _OLD file if exits if (!isBadorWrongPassword(ioe)) { perm = loadFromPath(backupPath, password); // Rename CURRENT to CORRUPTED renameOrFail(path, new Path(path.toString() + "_CORRUPTED_" + System.currentTimeMillis())); renameOrFail(backupPath, path); LOG.debug(String.format( "KeyStore loaded successfully from '%s' since '%s'" + "was corrupted !!", backupPath, path)); } else { throw ioe; } } return perm; }