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   View source code 8 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   View source code 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: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManager.java   View source code 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 4
Project: azure-libraries-for-java   File: HostNameSslBindingImpl.java   View source code 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 5
Project: Websocket-Smart-Card-Signer   File: X509Utils.java   View source code 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 6
Project: IJPay   File: CertUtil.java   View source code 6 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 7
Project: lams   File: EvaluableX509CertSelectorCredentialCriteria.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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);
}