Java Code Examples for java.security.cert.X509Certificate

The following are top voted examples for showing how to use java.security.cert.X509Certificate. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: revolution-irc   File: ServerCertificateManager.java   Source Code and License 9 votes vote down vote up
public static String buildCertAppliesToString(X509Certificate cert) {
    List<String> elements = new ArrayList<>();
    try {
        Collection<List<?>> altNames = cert.getSubjectAlternativeNames();
        if (altNames != null) {
            for (List<?> altName : altNames) {
                Integer altNameType = (Integer) altName.get(0);
                if (altNameType != 2 && altNameType != 7) // dns or ip
                    continue;
                elements.add((String) altName.get(1));
            }
        }
    } catch (CertificateParsingException ignored) {
    }

    if (elements.size() == 0)
        return "none";
    return TextUtils.join(",", elements.toArray());
}
 
Example 2
Project: installcert   File: InstallCert.java   Source Code and License 7 votes vote down vote up
public static String getCommonName(X509Certificate cert)
        throws InvalidNameException {
    // use LDAP API to parse the certifiate Subject :)
    // see http://stackoverflow.com/a/7634755/972463
    LdapName ldapDN
            = new LdapName(cert.getSubjectX500Principal().getName());
    String cn = "";
    for (Rdn rdn : ldapDN.getRdns()) {
        if (rdn.getType().equals("CN")) {
            cn = rdn.getValue().toString();
        }
    }
    return cn;
}
 
Example 3
Project: IJPay   File: CertUtil.java   Source Code and License 7 votes vote down vote up
/**
	 * 检查证书链
	 * 
	 * @param rootCerts
	 *            根证书
	 * @param cert
	 *            待验证的证书
	 * @return
	 */
	public static boolean verifyCertificate(X509Certificate cert) {
		
		if ( null == cert) {
			LogUtil.writeErrorLog("cert must Not null");
			return false;
		}
		try {
			cert.checkValidity();//验证有效期
//			cert.verify(middleCert.getPublicKey());
			if(!verifyCertificateChain(cert)){
				return false;
			}
		} catch (Exception e) {
			LogUtil.writeErrorLog("verifyCertificate fail", e);
			return false;
		}
		
		if(SDKConfig.getConfig().isIfValidateCNName()){
			// 验证公钥是否属于银联
			if(!UNIONPAY_CNNAME.equals(CertUtil.getIdentitiesFromCertficate(cert))) {
				LogUtil.writeErrorLog("cer owner is not CUP:" + CertUtil.getIdentitiesFromCertficate(cert));
				return false;
			}
		} else {
			// 验证公钥是否属于银联
			if(!UNIONPAY_CNNAME.equals(CertUtil.getIdentitiesFromCertficate(cert)) 
					&& !"00040000:SIGN".equals(CertUtil.getIdentitiesFromCertficate(cert))) {
				LogUtil.writeErrorLog("cer owner is not CUP:" + CertUtil.getIdentitiesFromCertficate(cert));
				return false;
			}
		}
		return true;		
	}
 
Example 4
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManager.java   Source Code and License 6 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(final String s) {
    return with(new Function<X509Certificate[]>() {

        @Override
        public X509Certificate[] apply(X509ExtendedKeyManager delegate) {
            return delegate.getCertificateChain(s);
        }

    });
}
 
Example 5
Project: azure-libraries-for-java   File: HostNameSslBindingImpl.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 6
Project: Websocket-Smart-Card-Signer   File: X509Utils.java   Source Code and License 6 votes vote down vote up
public static ArrayList<String> getDistributionPointUrls(X509Certificate cert){
    
    ArrayList<String> ret = new ArrayList<String>();
    
    try{
        String data = cert.toString();
        
        if(data.indexOf("CRLDistributionPoints") == -1)
            return ret;
        
        data = data.substring(data.indexOf("CRLDistributionPoints"));
        data = data.substring(0, data.indexOf("]]") + 2);
        
        while(data.indexOf("URIName") != -1){
            data = data.substring(data.indexOf("URIName") + 9);
            
            String url = data.substring(0, data.indexOf("]"));
            
            if(url.contains(", URIName: ")){
                String[] urlTmpList = url.split(", URIName: ");
                for(String urlTmp:urlTmpList)
                    ret.add(urlTmp);
            }else
                ret.add(url);
            
            data = data.substring(data.indexOf("]") + 1);
        }
    }catch(Exception ex){ex.printStackTrace();}
    
    return ret;
}
 
Example 7
Project: lams   File: EvaluableX509CertSelectorCredentialCriteria.java   Source Code and License 6 votes vote down vote up
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    if (!(target instanceof X509Credential)) {
        log.info("Credential is not an X509Credential, can not evaluate X509CertSelector criteria");
        return Boolean.FALSE;
    }
    X509Credential x509Cred = (X509Credential) target;

    X509Certificate entityCert = x509Cred.getEntityCertificate();
    if (entityCert == null) {
        log.info("X509Credential did not contain an entity certificate, can not evaluate X509CertSelector criteria");
        return Boolean.FALSE;
    }

    Boolean result = certSelector.match(entityCert);
    return result;
}
 
Example 8
Project: revolution-irc   File: UserOverrideTrustManager.java   Source Code and License 6 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    try {
        sDefaultTrustManager.checkServerTrusted(chain, authType);
    } catch (Exception e) {
        try {
            mManager.checkServerTrusted(chain, authType);
        } catch (Exception e2) {
            synchronized (UserOverrideTrustManager.this) {
                if (mTempTrustedCertificates != null && mTempTrustedCertificates.contains(chain[0])) {
                    Log.i(TAG, "A temporarily trusted certificate is being used - trusting the server");
                    return;
                }
            }
            Log.i(TAG, "Unrecognized certificate");
            try {
                X509Certificate cert = chain[0];
                if (!askUser(cert, R.string.certificate_bad_cert).get())
                    throw new UserRejectedCertificateException();
            } catch (InterruptedException | ExecutionException e3) {
                throw new CertificateException("Asking user about the certificate failed");
            }
        }
    }
}
 
Example 9
Project: jdk8u-jdk   File: KeyStore.java   Source Code and License 6 votes vote down vote up
/**
 * Generates a certificate chain from the collection of
 * certificates and stores the result into a key entry.
 */
private void generateCertificateChain(String alias,
    Collection<? extends Certificate> certCollection)
{
    try
    {
        X509Certificate[] certChain =
            new X509Certificate[certCollection.size()];

        int i = 0;
        for (Iterator<? extends Certificate> iter =
                certCollection.iterator(); iter.hasNext(); i++)
        {
            certChain[i] = (X509Certificate) iter.next();
        }

        storeWithUniqueAlias(alias,
                new KeyEntry(alias, null, certChain));
    }
    catch (Throwable e)
    {
        // Ignore the exception and skip this entry
        // TODO - throw CertificateException?
    }
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: TestTrustAllManager.java   Source Code and License 6 votes vote down vote up
@Test
public void testTrustAllManager() throws Exception {
  TrustAllManager manager = new TrustAllManager();
  manager.checkClientTrusted((X509Certificate[]) null, (String) null);
  manager.checkServerTrusted((X509Certificate[]) null, (String) null);

  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);

  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);
  Assert.assertEquals(manager.getAcceptedIssuers() == null, true);
}
 
Example 11
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 6 votes vote down vote up
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
    for (final X509TrustManager trustManager : trustManagers) {
        try {
            trustManager.checkServerTrusted(chain, authType);
            return;
        } catch (final CertificateException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }
    throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
 
Example 12
Project: dcos-maven-plugin   File: DcosPluginHelper.java   Source Code and License 6 votes vote down vote up
@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();
  }
}
 
Example 13
Project: SecuritySample   File: ExtendedKeyUsageImpl.java   Source Code and License 5 votes vote down vote up
public ExtendedKeyUsageImpl(X509Certificate cert) throws IOException {
	keyPurposeIds = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.extendedKeyUsage.getId());
	if (extVal == null)
		return;
	org.bouncycastle.asn1.x509.ExtendedKeyUsage usage = org.bouncycastle.asn1.x509.ExtendedKeyUsage
			.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	KeyPurposeId[] usages = usage.getUsages();
	for (int i = 0; i < usages.length; i++) {
		keyPurposeIds.add(usages[i].getId());
	}
}
 
Example 14
Project: SecuritySample   File: BasicConstraintsImpl.java   Source Code and License 5 votes vote down vote up
public BasicConstraintsImpl(X509Certificate cert) throws CertificateException, IOException {
	byte[] extVal = cert.getExtensionValue(Extension.basicConstraints.getId());
	if (extVal == null)
		return;
	org.bouncycastle.asn1.x509.BasicConstraints bc = org.bouncycastle.asn1.x509.BasicConstraints
			.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	isCA = bc.isCA();
	pathLen = bc.getPathLenConstraint();
}
 
Example 15
Project: openjdk-jdk10   File: RetrievalMethodResolver.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves a x509Certificate from the given information
 * @param e
 * @param baseURI
 * @param storage
 * @return
 * @throws KeyResolverException
 */
private static X509Certificate resolveCertificate(
    Element e, String baseURI, StorageResolver storage
) throws KeyResolverException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
            + e.getLocalName() + " Element");
    }
    // An element has been provided
    if (e != null) {
        return KeyResolver.getX509Certificate(e, baseURI, storage);
    }
    return null;
}
 
Example 16
Project: jdk8u-jdk   File: X509IssuerSerialResolver.java   Source Code and License 5 votes vote down vote up
/** @inheritDoc */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {

    X509Certificate cert =
        this.engineLookupResolveX509Certificate(element, baseURI, storage);

    if (cert != null) {
        return cert.getPublicKey();
    }

    return null;
}
 
Example 17
Project: cas-5.1.0   File: X509SerialNumberPrincipalResolverTests.java   Source Code and License 5 votes vote down vote up
@Test
public void verifyHexPrincipalEven() {
    final X509SerialNumberPrincipalResolver r = new X509SerialNumberPrincipalResolver(16, true);
    final X509Certificate mockCert = mock(X509Certificate.class);
    when(mockCert.getSerialNumber()).thenReturn(BigInteger.valueOf(60300L));

    final String principal = r.resolvePrincipalInternal(mockCert);
    assertEquals("eb8c", principal);
}
 
Example 18
Project: ipack   File: AttributeCertificateIssuer.java   Source Code and License 5 votes vote down vote up
public boolean match(Object obj)
{
    if (!(obj instanceof X509Certificate))
    {
        return false;
    }

    return match((Certificate)obj);
}
 
Example 19
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
    for (final X509TrustManager trustManager : trustManagers) {
        try {
            trustManager.checkServerTrusted(chain, authType);
            return;
        } catch (final CertificateException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }
    throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
 
Example 20
Project: openjdk-jdk10   File: ConstraintsChecker.java   Source Code and License 5 votes vote down vote up
/**
 * Internal method to check the name constraints against a cert
 */
private void verifyNameConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "name constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
    }

    // check name constraints only if there is a previous name constraint
    // and either the currCert is the final cert or the currCert is not
    // self-issued
    if (prevNC != null && ((i == certPathLength) ||
            !X509CertImpl.isSelfIssued(currCert))) {
        if (debug != null) {
            debug.println("prevNC = " + prevNC +
                ", currDN = " + currCert.getSubjectX500Principal());
        }

        try {
            if (!prevNC.verify(currCert)) {
                throw new CertPathValidatorException(msg + " check failed",
                    null, null, -1, PKIXReason.INVALID_NAME);
            }
        } catch (IOException ioe) {
            throw new CertPathValidatorException(ioe);
        }
    }

    // merge name constraints regardless of whether cert is self-issued
    prevNC = mergeNameConstraints(currCert, prevNC);

    if (debug != null)
        debug.println(msg + " verified.");
}
 
Example 21
Project: OpenJSharp   File: X509CertPath.java   Source Code and License 5 votes vote down vote up
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
 
Example 22
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
    final List<X509Certificate> certificates = new ArrayList<>();
    for (final X509TrustManager trustManager : trustManagers) {
        final List<X509Certificate> list = Arrays.asList(trustManager.getAcceptedIssuers());
        certificates.addAll(list);
    }
    return certificates.toArray(new X509Certificate[] {});
}
 
Example 23
Project: verify-matching-service-adapter   File: FixedCertificateChainValidatorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void validate_shouldFailACertSignedByAnUnknownRootCACert() throws Exception {
    final X509Certificate otherChildCertificate =
            certificateFactory.createCertificate(childSignedByOtherRootCAString);

    assertExceptionMessage(
            certificateChainValidator,
            otherChildCertificate,
            CertificateChainValidationException.class,
            "Certificate is not valid: O=other_server, CN=localhost"
    );
}
 
Example 24
Project: openjdk-jdk10   File: SimpleOCSPServer.java   Source Code and License 5 votes vote down vote up
/**
 * Construct a SimpleOCSPServer using specific network parameters,
 * keystore, password, and alias.
 *
 * @param addr the address to bind the server to.  A value of {@code null}
 * means the server will bind to all interfaces.
 * @param port the port to listen on.  A value of {@code 0} will mean that
 * the server will randomly pick an open ephemeral port to bind to.
 * @param ks the keystore to be used
 * @param password the password to access key material in the keystore
 * @param issuerAlias the alias of the issuer certificate
 * @param signerAlias the alias of the signer certificate and key.  A
 * value of {@code null} means that the {@code issuerAlias} will be used
 * to look up the signer key.
 *
 * @throws GeneralSecurityException if there are problems accessing the
 * keystore or finding objects within the keystore.
 * @throws IOException if a {@code ResponderId} cannot be generated from
 * the signer certificate.
 */
public SimpleOCSPServer(InetAddress addr, int port, KeyStore ks,
        String password, String issuerAlias, String signerAlias)
        throws GeneralSecurityException, IOException {
    Objects.requireNonNull(ks, "Null keystore provided");
    Objects.requireNonNull(issuerAlias, "Null issuerName provided");

    utcDateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    keystore = ks;
    issuerCert = (X509Certificate)ks.getCertificate(issuerAlias);
    if (issuerCert == null) {
        throw new IllegalArgumentException("Certificate for alias " +
                issuerAlias + " not found");
    }

    if (signerAlias != null) {
        signerCert = (X509Certificate)ks.getCertificate(signerAlias);
        if (signerCert == null) {
            throw new IllegalArgumentException("Certificate for alias " +
                signerAlias + " not found");
        }
        signerKey = (PrivateKey)ks.getKey(signerAlias,
                password.toCharArray());
        if (signerKey == null) {
            throw new IllegalArgumentException("PrivateKey for alias " +
                signerAlias + " not found");
        }
    } else {
        signerCert = issuerCert;
        signerKey = (PrivateKey)ks.getKey(issuerAlias,
                password.toCharArray());
        if (signerKey == null) {
            throw new IllegalArgumentException("PrivateKey for alias " +
                issuerAlias + " not found");
        }
    }

    sigAlgId = AlgorithmId.get("Sha256withRSA");
    respId = new ResponderId(signerCert.getSubjectX500Principal());
    listenAddress = addr;
    listenPort = port;
}
 
Example 25
Project: jdk8u-jdk   File: X509CertPath.java   Source Code and License 5 votes vote down vote up
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
 
Example 26
Project: OutsourcedProject   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate certificates[],
                               String authType) throws CertificateException {
    if (this.certificates == null) {
        this.certificates = certificates;
        log.info("init at checkClientTrusted");
    }


}
 
Example 27
Project: ARCLib   File: CertificateDecoder.java   Source Code and License 5 votes vote down vote up
public X509Certificate decode(String certStr) {
    try {
        byte[] decoded = Base64.getDecoder().decode(certStr);

        return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(decoded));
    } catch (IllegalArgumentException | CertificateException e) {
        log.warn("Failed to decode certificate {}.", certStr);
        return null;
    }
}
 
Example 28
Project: aos-FileCoreLibrary   File: FTPSTrustManager.java   Source Code and License 5 votes vote down vote up
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException
{
    for (X509Certificate certificate : certificates)
    {
        certificate.checkValidity();
    }
}
 
Example 29
Project: springboot-shiro-cas-mybatis   File: PoolingLdaptiveResourceCRLFetcherTests.java   Source Code and License 5 votes vote down vote up
@Test
public void getCrlFromLdapWithNoCaching() throws Exception {
    for (int i = 0; i < 10; i++) {
        CacheManager.getInstance().removeAllCaches();
        final Cache cache = new Cache("crlCache-1", 100, false, false, 20, 10);
        CacheManager.getInstance().addCache(cache);
        final CRLDistributionPointRevocationChecker checker = new CRLDistributionPointRevocationChecker(cache, fetcher);
        checker.setThrowOnFetchFailure(true);
        checker.setUnavailableCRLPolicy(new AllowRevocationPolicy());
        final X509Certificate cert = CertUtils.readCertificate(new ClassPathResource("ldap-crl.crt"));
        checker.check(cert);
    }
}
 
Example 30
Project: Java_CTe   File: Assinatura.java   Source Code and License 5 votes vote down vote up
private static void loadCertificates(XMLSignatureFactory signatureFactory) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException, CertificadoException {

        Certificado certificado = configuracoesCte.getCertificado();
        KeyStore keyStore = CertificadoService.getKeyStore(certificado);
        KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(certificado.getNome(), new KeyStore.PasswordProtection(certificado.getSenha().toCharArray()));
        privateKey = pkEntry.getPrivateKey();

        KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
        List<X509Certificate> x509Content = new ArrayList<X509Certificate>();

        x509Content.add(CertificadoService.getCertificate(certificado, keyStore));
        X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
        keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
    }
 
Example 31
Project: lams   File: KeyInfoHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Build an {@link X509Digest} containing the digest of the specified certificate.
 * 
 * @param javaCert the Java X509Certificate to digest
 * @param algorithmURI  digest algorithm URI
 * @return a new X509Digest object
 * @throws NoSuchAlgorithmException if the algorithm specified cannot be used
 * @throws CertificateEncodingException if the certificate cannot be encoded
 */
public static X509Digest buildX509Digest(X509Certificate javaCert, String algorithmURI)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    
    String jceAlg = SecurityHelper.getAlgorithmIDFromURI(algorithmURI);
    if (jceAlg == null) {
        throw new NoSuchAlgorithmException("No JCE algorithm found for " + algorithmURI);
    }
    MessageDigest md = MessageDigest.getInstance(jceAlg);
    byte[] hash = md.digest(javaCert.getEncoded());
    
    X509Digest xmlDigest = (X509Digest) Configuration.getBuilderFactory()
        .getBuilder(X509Digest.DEFAULT_ELEMENT_NAME)
        .buildObject(X509Digest.DEFAULT_ELEMENT_NAME);
    xmlDigest.setAlgorithm(algorithmURI);
    xmlDigest.setValue(Base64.encodeBytes(hash));
    
    return xmlDigest;
}
 
Example 32
Project: verify-hub   File: ConfigServiceKeyStore.java   Source Code and License 5 votes vote down vote up
private void validate(final X509Certificate certificate, final KeyStore trustStore) {
    CertificateValidity certificateValidity = certificateChainValidator.validate(certificate, trustStore);
    if (!certificateValidity.isValid()) {
        throw new CertificateChainValidationException(
                format("Certificate is not valid: {0}", getDnForCertificate(certificate)),
                certificateValidity.getException().get());
    }
}
 
Example 33
Project: okhttpUtil   File: HttpsUtil.java   Source Code and License 5 votes vote down vote up
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
	// TODO Auto-generated method stub
        try
        {
            defaultTrustManager.checkServerTrusted(arg0, arg1);
        } catch (CertificateException ce)
        {
            localTrustManager.checkServerTrusted(arg0, arg1);
        }
}
 
Example 34
Project: ARCLib   File: PathCertificateFilter.java   Source Code and License 5 votes vote down vote up
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    X509Certificate cert = extractClientCertificate(request);

    if (cert == null) {
        return null;
    }

    return principalExtractor.extractPrincipal(cert);
}
 
Example 35
Project: zabbkit-android   File: LoginActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCertificateRequest(final X509Certificate[] certificate) {
    dismissDialog();
    if (certificate == null) {
        performLogin();
    } else {
        DialogHelper.showSslDialog(LoginActivity.this,
                certificate, LoginActivity.this);
    }

}
 
Example 36
Project: jdk8u-jdk   File: BasicChecker.java   Source Code and License 5 votes vote down vote up
/**
 * Internal method to check that cert has a valid DN to be next in a chain
 */
private void verifyNameChaining(X509Certificate cert)
    throws CertPathValidatorException
{
    if (prevSubject != null) {

        String msg = "subject/issuer name chaining";
        if (debug != null)
            debug.println("---checking " + msg + "...");

        X500Principal currIssuer = cert.getIssuerX500Principal();

        // reject null or empty issuer DNs
        if (X500Name.asX500Name(currIssuer).isEmpty()) {
            throw new CertPathValidatorException
                (msg + " check failed: " +
                 "empty/null issuer DN in certificate is invalid", null,
                 null, -1, PKIXReason.NAME_CHAINING);
        }

        if (!(currIssuer.equals(prevSubject))) {
            throw new CertPathValidatorException
                (msg + " check failed", null, null, -1,
                 PKIXReason.NAME_CHAINING);
        }

        if (debug != null)
            debug.println(msg + " verified.");
    }
}
 
Example 37
Project: openjdk-jdk10   File: SSLServerCertStore.java   Source Code and License 5 votes vote down vote up
private static List<X509Certificate> getMatchingCerts
    (List<X509Certificate> certs, CertSelector selector)
{
    // if selector not specified, all certs match
    if (selector == null) {
        return certs;
    }
    List<X509Certificate> matchedCerts = new ArrayList<>(certs.size());
    for (X509Certificate cert : certs) {
        if (selector.match(cert)) {
            matchedCerts.add(cert);
        }
    }
    return matchedCerts;
}
 
Example 38
Project: https-github.com-apache-zookeeper   File: X509AuthTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testTrustedAuth() {
    X509AuthenticationProvider provider = createProvider(clientCert);
    MockServerCnxn cnxn = new MockServerCnxn();
    cnxn.clientChain = new X509Certificate[] { clientCert };
    Assert.assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null));
}
 
Example 39
Project: atlas   File: LocalSignedJarBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.
 *
 * @param out         the {@link OutputStream} where to write the Jar archive.
 * @param key         the {@link PrivateKey} used to sign the archive, or <code>null</code>.
 * @param certificate the {@link X509Certificate} used to sign the archive, or
 *                    <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public LocalSignedJarBuilder(@NonNull OutputStream out,
                             @Nullable PrivateKey key,
                             @Nullable X509Certificate certificate,
                             @Nullable String builtBy,
                             @Nullable String createdBy,
                             @Nullable String signFile) throws IOException, NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;
    mSignFile = signFile;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version", "1.0");
        if (builtBy != null) {
            main.putValue("Built-By", builtBy);
        }
        if (createdBy != null) {
            main.putValue("Created-By", createdBy);
        }

        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}
 
Example 40
Project: FApkSigner   File: ApkSigner.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a new {@code Builder}.
 *
 * @param name signer's name. The name is reflected in the name of files comprising the
 *        JAR signature of the APK.
 * @param privateKey signing key
 * @param certificates list of one or more X.509 certificates. The subject public key of
 *        the first certificate must correspond to the {@code privateKey}.
 */
public Builder(
        String name,
        PrivateKey privateKey,
        List<X509Certificate> certificates) {
    if (name.isEmpty()) {
        throw new IllegalArgumentException("Empty name");
    }
    mName = name;
    mPrivateKey = privateKey;
    mCertificates = new ArrayList<>(certificates);
}
 
Example 41
Project: mobile-store   File: IndexV1Updater.java   Source Code and License 5 votes vote down vote up
/**
 * Verify that the signing certificate used to sign {@link #SIGNED_FILE_NAME}
 * matches the signing stored in the database for this repo.  {@link #repo} and
 * {@code repo.signingCertificate} must be pre-loaded from the database before
 * running this, if this is an existing repo.  If the repo does not exist,
 * this will run the TOFU process.
 * <p>
 * Index V1 works with two copies of the signing certificate:
 * <li>in the downloaded jar</li>
 * <li>stored in the local database</li>
 * <p>
 * A new repo can be added with or without the fingerprint of the signing
 * certificate.  If no fingerprint is supplied, then do a pure TOFU and just
 * store the certificate as valid.  If there is a fingerprint, then first
 * check that the signing certificate in the jar matches that fingerprint.
 * <p>
 * This is also responsible for adding the {@link Repo} instance to the
 * database for the first time.
 * <p>
 * This is the same as {@link RepoUpdater#verifyCerts(String, X509Certificate)},
 * {@link RepoUpdater#verifyAndStoreTOFUCerts(String, X509Certificate)}, and
 * {@link RepoUpdater#assertSigningCertFromXmlCorrect()} except there is no
 * embedded copy of the signing certificate in the index data.
 *
 * @param rawCertFromJar the {@link X509Certificate} embedded in the downloaded jar
 * @see RepoUpdater#verifyAndStoreTOFUCerts(String, X509Certificate)
 * @see RepoUpdater#verifyCerts(String, X509Certificate)
 * @see RepoUpdater#assertSigningCertFromXmlCorrect()
 */
private void verifySigningCertificate(X509Certificate rawCertFromJar) throws SigningException {
    String certFromJar = Hasher.hex(rawCertFromJar);

    if (TextUtils.isEmpty(certFromJar)) {
        throw new SigningException(repo,
                SIGNED_FILE_NAME + " must have an included signing certificate!");
    }

    if (repo.signingCertificate == null) {
        if (repo.fingerprint != null) {
            String fingerprintFromJar = Utils.calcFingerprint(rawCertFromJar);
            if (!repo.fingerprint.equalsIgnoreCase(fingerprintFromJar)) {
                throw new SigningException(repo,
                        "Supplied certificate fingerprint does not match!");
            }
        }
        Utils.debugLog(TAG, "Saving new signing certificate to database for " + repo.address);
        ContentValues values = new ContentValues(2);
        values.put(Schema.RepoTable.Cols.LAST_UPDATED, Utils.formatDate(new Date(), ""));
        values.put(Schema.RepoTable.Cols.SIGNING_CERT, Hasher.hex(rawCertFromJar));
        RepoProvider.Helper.update(context, repo, values);
        repo.signingCertificate = certFromJar;
    }

    if (TextUtils.isEmpty(repo.signingCertificate)) {
        throw new SigningException(repo, "A empty repo signing certificate is invalid!");
    }

    if (repo.signingCertificate.equals(certFromJar)) {
        return; // we have a match!
    }

    throw new SigningException(repo, "Signing certificate does not match!");
}
 
Example 42
Project: cas4.0.x-server-wechat   File: CRLDistributionPointRevocationChecker.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @see AbstractCRLRevocationChecker#getCRL(X509Certificate)
 */
@Override
protected X509CRL getCRL(final X509Certificate cert) {
    final URL[] urls = getDistributionPoints(cert);
    logger.debug(String.format(
            "Distribution points for %s: %s.",
            CertUtils.toString(cert), Arrays.asList(urls)));

    Element item;
    for (URL url : urls) {
        item = this.crlCache.get(url);
        if (item != null) {
            logger.debug("Found CRL in cache for {}", CertUtils.toString(cert));
            return (X509CRL) item.getObjectValue();
        }
    }

    // Try all distribution points and stop at first fetch that succeeds
    X509CRL crl = null;
    for (int i = 0; i < urls.length && crl == null; i++) {
        logger.info("Attempting to fetch CRL at {}", urls[i]);
        try {
            crl = CertUtils.fetchCRL(new UrlResource(urls[i]));
            logger.info("Success. Caching fetched CRL.");
            this.crlCache.put(new Element(urls[i], crl));
        } catch (final Exception e) {
            logger.error("Error fetching CRL at {}", urls[i], e);
        }
    }

    return crl;
}
 
Example 43
Project: GitHub   File: URLConnectionTest.java   Source Code and License 5 votes vote down vote up
private String certificatesToString(X509Certificate[] certificates) {
  List<String> result = new ArrayList<>();
  for (X509Certificate certificate : certificates) {
    result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber());
  }
  return result.toString();
}
 
Example 44
Project: Relay   File: X509TrustAll.java   Source Code and License 4 votes vote down vote up
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
		throws CertificateException {
}
 
Example 45
Project: mobile-store   File: LocalRepoKeyStore.java   Source Code and License 4 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(String alias) {
    return wrapped.getCertificateChain(alias);
}
 
Example 46
Project: framework   File: WebUtils.java   Source Code and License 4 votes vote down vote up
public X509Certificate[] getAcceptedIssuers() {
	return null;
}
 
Example 47
Project: jetfuel   File: X509TrustManager.java   Source Code and License 4 votes vote down vote up
public void checkServerTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
	// do nothing

}
 
Example 48
Project: cyberduck   File: CertificateStoreX509TrustManager.java   Source Code and License 4 votes vote down vote up
@Override
public void checkClientTrusted(final X509Certificate[] x509Certificates, final String cipher)
        throws CertificateException {

    this.verify(x509Certificates, cipher);
}
 
Example 49
Project: ipack   File: JcaSimpleSignerInfoVerifierBuilder.java   Source Code and License 4 votes vote down vote up
ContentVerifierProvider createContentVerifierProvider(X509Certificate certificate)
    throws OperatorCreationException
{
    return new JcaContentVerifierProviderBuilder().setProvider(provider).build(certificate);
}
 
Example 50
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   Source Code and License 4 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
}
 
Example 51
Project: aliyun-cloudphotos-android-demo   File: SSLUtil.java   Source Code and License 4 votes vote down vote up
public void checkClientTrusted(X509Certificate[] certs, String authType)
        throws CertificateException {
    return;
}
 
Example 52
Project: jdk8u-jdk   File: X509CertificatePair.java   Source Code and License 4 votes vote down vote up
/**
 * Sets the forward component of the certificate pair.
 */
public void setForward(X509Certificate cert) throws CertificateException {
    checkPair();
    forward = cert;
}
 
Example 53
Project: OpenJSharp   File: Main.java   Source Code and License 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 54
Project: bubichain-sdk-java   File: ServiceConnectionManager.java   Source Code and License 4 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers(){
    return null;
}
 
Example 55
Project: XDroid-Databinding   File: HttpsManager.java   Source Code and License 4 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
}
 
Example 56
Project: revolution-irc   File: UserOverrideTrustManager.java   Source Code and License 4 votes vote down vote up
public SSLCertWarning(X509Certificate certificate, int stringId, Object[] stringArgs) {
    mCertificate = certificate;
    mStringId = stringId;
    mStringArgs = stringArgs;
    mReturnValue = new SettableFuture<>();
}
 
Example 57
Project: satisfy   File: SSLUtils.java   Source Code and License 4 votes vote down vote up
public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[]{};
}
 
Example 58
Project: openjdk-jdk10   File: TrustAnchors.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (initSecmod() == false) {
        return;
    }

    // our secmod.db file says nssckbi.*so*, so NSS does not find the
    // *DLL* on Windows nor the *DYLIB* on Mac OSX.
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.startsWith("win") || osName.startsWith("mac")) {
        System.out.println("Test currently does not work on " + osName +
            ", skipping");
        return;
    }

    String configName = BASE + SEP + "nsstrust.cfg";
    Provider p = getSunPKCS11(configName);

    System.out.println(p);
    Security.addProvider(p);

    if (args.length > 1 && "sm".equals(args[0])) {
        System.setProperty("java.security.policy",
                BASE + File.separator + args[1]);
        System.setSecurityManager(new SecurityManager());
    }

    KeyStore ks = KeyStore.getInstance("PKCS11", p);
    ks.load(null, null);
    Collection<String> aliases = new TreeSet<>(Collections.list(ks.aliases()));
    System.out.println("entries: " + aliases.size());
    System.out.println(aliases);

    for (String alias : aliases) {
        if (ks.isCertificateEntry(alias) == false) {
            throw new Exception("not trusted: " + alias);
        }
        X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
        // verify self-signed certs
        if (cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
        System.out.print(".");
            cert.verify(cert.getPublicKey());
        } else {
            System.out.print("-");
        }
    }

    System.out.println();
    System.out.println("OK");
}
 
Example 59
Project: mtls-sample   File: SerialNumberExtractor.java   Source Code and License 4 votes vote down vote up
String getSerialNumber(Principal principal) {
    X509Certificate certificate = (X509Certificate) ((PreAuthenticatedAuthenticationToken) principal).getCredentials();
    return certificate.getSerialNumber().toString();
}
 
Example 60
Project: httpclient   File: Certificate.java   Source Code and License 4 votes vote down vote up
private X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
	CertificateFactory factory = CertificateFactory.getInstance("X.509");

	return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
}