List of usage examples for java.security.cert CertificateException CertificateException
public CertificateException(Throwable cause)
From source file:mobac.mapsources.loader.MapPackManager.java
/** * Verifies the class file signatures of the specified map pack * //www.j a va2s . c o m * @param mapPackFile * @throws IOException * @throws CertificateException */ public void testMapPack(File mapPackFile) throws IOException, CertificateException { String fileName = mapPackFile.getName(); JarFile jf = new JarFile(mapPackFile, true); try { Enumeration<JarEntry> it = jf.entries(); while (it.hasMoreElements()) { JarEntry entry = it.nextElement(); // We verify only class files if (!entry.getName().endsWith(".class")) continue; // directory or other entry // Get the input stream (triggers) the signature verification for the specific class Utilities.readFully(jf.getInputStream(entry)); if (entry.getCodeSigners() == null) throw new CertificateException("Unsigned class file found: " + entry.getName()); CodeSigner signer = entry.getCodeSigners()[0]; List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates(); if (cp.size() > 1) throw new CertificateException("Signature certificate not accepted: " + "certificate path contains more than one certificate"); // Compare the used certificate with the mapPack certificate if (!mapPackCert.equals(cp.get(0))) throw new CertificateException( "Signature certificate not accepted: " + "not the MapPack signer certificate"); } Manifest mf = jf.getManifest(); Attributes a = mf.getMainAttributes(); String mpv = a.getValue("MapPackVersion"); if (mpv == null) throw new IOException("MapPackVersion info missing!"); int mapPackVersion = Integer.parseInt(mpv); if (requiredMapPackVersion != mapPackVersion) throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version."); ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource"); if (entry == null) throw new IOException("MapSources services list is missing in file " + fileName); } finally { jf.close(); } }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private X509Certificate findCertIssuerInStore(X509Certificate x509cert, KeyStore kStore) throws CertificateException { X509Certificate x509issuer = null; debug("searching store for issuer: " + x509cert.getIssuerDN()); // check in our local root CA Store Enumeration<String> enumAliases; try {// w w w .j av a 2 s. c o m enumAliases = kStore.aliases(); X509Certificate x509search = null; while (enumAliases.hasMoreElements()) { x509search = (X509Certificate) kStore.getCertificate(enumAliases.nextElement()); if (checkSubjectMatchesIssuer(x509search.getSubjectX500Principal(), x509cert.getIssuerX500Principal())) { x509issuer = x509search; debug("found issuer for current cert in chain in ROOT CA store: " + x509issuer.getSubjectDN()); break; } } } catch (KeyStoreException e) { String errMsg = mContext.getString(R.string.error_problem_access_local_root_ca_store); debug(errMsg); throw new CertificateException(errMsg); } return x509issuer; }
From source file:com.irccloud.android.NetworkConnection.java
@SuppressWarnings("deprecation") public NetworkConnection() { String version;/*from w ww . j a va 2 s . c o m*/ String network_type = null; try { version = "/" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo( IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName; } catch (Exception e) { version = ""; } try { ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null) network_type = ni.getTypeName(); } catch (Exception e) { } try { config = new JSONObject(PreferenceManager .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()) .getString("config", "{}")); } catch (JSONException e) { e.printStackTrace(); config = new JSONObject(); } useragent = "IRCCloud" + version + " (" + android.os.Build.MODEL + "; " + Locale.getDefault().getCountry().toLowerCase() + "; " + "Android " + android.os.Build.VERSION.RELEASE; WindowManager wm = (WindowManager) IRCCloudApplication.getInstance() .getSystemService(Context.WINDOW_SERVICE); useragent += "; " + wm.getDefaultDisplay().getWidth() + "x" + wm.getDefaultDisplay().getHeight(); if (network_type != null) useragent += "; " + network_type; useragent += ")"; WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); wifiLock = wfm.createWifiLock(TAG); kms = new X509ExtendedKeyManager[1]; kms[0] = new X509ExtendedKeyManager() { @Override public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { return SSLAuthAlias; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { throw new UnsupportedOperationException(); } @Override public X509Certificate[] getCertificateChain(String alias) { return SSLAuthCertificateChain; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { throw new UnsupportedOperationException(); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { throw new UnsupportedOperationException(); } @Override public PrivateKey getPrivateKey(String alias) { return SSLAuthKey; } }; tms = new TrustManager[1]; tms[0] = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException("Not implemented"); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509"); trustManagerFactory.init((KeyStore) null); for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { X509TrustManager x509TrustManager = (X509TrustManager) trustManager; x509TrustManager.checkServerTrusted(chain, authType); } } } catch (KeyStoreException e) { throw new CertificateException(e); } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } if (BuildConfig.SSL_FPS != null && BuildConfig.SSL_FPS.length > 0) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] sha1 = md.digest(chain[0].getEncoded()); // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java final char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[sha1.length * 2]; for (int j = 0; j < sha1.length; j++) { int v = sha1[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } String hexCharsStr = new String(hexChars); boolean matched = false; for (String fp : BuildConfig.SSL_FPS) { if (fp.equals(hexCharsStr)) { matched = true; break; } } if (!matched) throw new CertificateException("Incorrect CN in cert chain"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; WebSocketClient.setTrustManagers(tms); }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate *///w ww . j a v a 2s .co m public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private void checkStrongCrypto(X509Certificate cert) throws CertificateException { String algo = cert.getSigAlgName().toLowerCase(); if (algo.contains("md5")) { debug("cert uses weak crypto: " + algo); if (mNotifyVerificationFail) showCertMessage(mContext.getString(R.string.warning_weak_crypto), cert.getIssuerDN().getName(), cert, null);/*from w w w .j a v a 2 s. com*/ throw new CertificateException("issuer uses weak crypto: " + algo); } }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate *///from ww w.ja v a 2 s.c om public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // (3) subjectAlternativeName if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java
/** * Calculates the hash of the certificate known as the "thumbprint" * and returns it as a string representation. * * @param cert The certificate to hash./* w w w. j a va 2 s. c o m*/ * @param algorithm The hash algorithm to use. * @return The SHA-1 hash of the certificate. * @throws CertificateException */ private static String getThumbprint(Certificate cert, String algorithm) throws CertificateException { MessageDigest digest; try { digest = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } byte[] encodedCert = cert.getEncoded(); StringBuilder sb = new StringBuilder(encodedCert.length * 2); Formatter f = new Formatter(sb); try { for (byte b : digest.digest(encodedCert)) f.format("%02x", b); } finally { f.close(); } return sb.toString(); }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static X509CertInfo createX509CertInfo(X509Key x509key, BigInteger serialno, String issuername, String subjname, Date notBefore, Date notAfter) throws IOException, CertificateException, InvalidKeyException { // set default; use the other call with "alg" to set algorithm String alg = "SHA256withRSA"; try {//from www . ja v a 2 s.co m return createX509CertInfo(x509key, serialno, issuername, subjname, notBefore, notAfter, alg); } catch (NoSuchAlgorithmException ex) { // for those that calls the old call without alg throw new CertificateException("createX509CertInfo old call should not be here"); } }