Java Code Examples for java.security.cert.X509Certificate#getPublicKey()

The following examples show how to use java.security.cert.X509Certificate#getPublicKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticatedClientRequestHandler.java    From protect with MIT License 6 votes vote down vote up
/**
 * Attempts to map the end-entity certificate from the SSLSession to a known
 * public key from the given key loader. If it can be mapped will return an
 * integer for that entity. Otherwise will return null.
 * 
 * Note this may be used with either a client or server key loader.
 * 
 * @param keyLoader
 * @param session
 * @return
 */
protected static String determineUsername(final KeyLoader keyLoader, final SSLSession sslSession) {

	try {
		final Certificate[] certs = sslSession.getPeerCertificates();
		final X509Certificate peerCertificate = (X509Certificate) certs[0];
		final PublicKey peerPublicKey = peerCertificate.getPublicKey();

		// Attempt to link the public key in the certificate to a known entity's key
		return keyLoader.getUsername(peerPublicKey);

	} catch (SSLPeerUnverifiedException e) {
		// The client did not provide a certificate
		return null;
	}
}
 
Example 2
Source File: OCSPResponse.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
IssuerInfo(TrustAnchor anchor, X509Certificate issuerCert) {
    if (anchor == null && issuerCert == null) {
        throw new NullPointerException("TrustAnchor and issuerCert " +
                "cannot be null");
    }
    this.anchor = anchor;
    if (issuerCert != null) {
        name = issuerCert.getSubjectX500Principal();
        pubKey = issuerCert.getPublicKey();
        certificate = issuerCert;
    } else {
        name = anchor.getCA();
        pubKey = anchor.getCAPublicKey();
        certificate = anchor.getTrustedCert();
    }
}
 
Example 3
Source File: JwtTokenExtractorTests.java    From botbuilder-java with MIT License 6 votes vote down vote up
private static TokenValidationParameters createTokenValidationParameters(X509Certificate cert)
{
    return new TokenValidationParameters() {{
        validateIssuer = false;
        validIssuers = Collections.singletonList(AuthenticationConstants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER);

        // Audience validation takes place in JwtTokenExtractor
        validateAudience = false;
        validateLifetime = true;
        clockSkew = Duration.ofMinutes(5);
        requireSignedTokens = true;

        // provide a custom resolver so that calls to openid won't happen (which wouldn't
        // work for these tests).
        issuerSigningKeyResolver = key -> (OpenIdMetadata) keyId -> {
            // return our certificate data
            OpenIdMetadataKey key1 = new OpenIdMetadataKey();
            key1.key = (RSAPublicKey) cert.getPublicKey();
            key1.certificateChain = Collections.singletonList(encodeCertificate(cert));
            return key1;
        };
    }};
}
 
Example 4
Source File: BasicChecker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to manage state information at each iteration
 */
private void updateState(X509Certificate currCert)
    throws CertPathValidatorException
{
    PublicKey cKey = currCert.getPublicKey();
    if (debug != null) {
        debug.println("BasicChecker.updateState issuer: " +
            currCert.getIssuerX500Principal().toString() + "; subject: " +
            currCert.getSubjectX500Principal() + "; serial#: " +
            currCert.getSerialNumber().toString());
    }
    if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
        // cKey needs to inherit DSA parameters from prev key
        cKey = makeInheritedParamsKey(cKey, prevPubKey);
        if (debug != null) debug.println("BasicChecker.updateState Made " +
                                         "key with inherited params");
    }
    prevPubKey = cKey;
    prevSubject = currCert.getSubjectX500Principal();
}
 
Example 5
Source File: X509CertificateResolver.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method engineResolvePublicKey
 * @inheritDoc
 * @param element
 * @param BaseURI
 * @param storage
 *
 * @throws KeyResolverException
 */
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 6
Source File: X509DigestResolver.java    From TencentKona-8 with GNU General Public License v2.0 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 7
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Recursively tries to establish chain from pool of trusted certs.
 *
 * @param certToVerify the cert that needs to be verified.
 * @param chain the chain that's being built.
 * @param certs the pool of trusted certs
 *
 * @return true if successful, false otherwise.
 */
private boolean buildChain(X509Certificate certToVerify,
                    Vector<Certificate> chain,
                    Hashtable<Principal, Vector<Certificate>> certs) {
    Principal issuer = certToVerify.getIssuerDN();
    if (isSelfSigned(certToVerify)) {
        // reached self-signed root cert;
        // no verification needed because it's trusted.
        chain.addElement(certToVerify);
        return true;
    }

    // Get the issuer's certificate(s)
    Vector<Certificate> vec = certs.get(issuer);
    if (vec == null) {
        return false;
    }

    // Try out each certificate in the vector, until we find one
    // whose public key verifies the signature of the certificate
    // in question.
    for (Enumeration<Certificate> issuerCerts = vec.elements();
         issuerCerts.hasMoreElements(); ) {
        X509Certificate issuerCert
            = (X509Certificate)issuerCerts.nextElement();
        PublicKey issuerPubKey = issuerCert.getPublicKey();
        try {
            certToVerify.verify(issuerPubKey);
        } catch (Exception e) {
            continue;
        }
        if (buildChain(issuerCert, chain, certs)) {
            chain.addElement(certToVerify);
            return true;
        }
    }
    return false;
}
 
Example 8
Source File: SignatureVerifier.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
protected void setSigPublicKeyFromXml(String xml, DocumentBuilder docBuilderNSTrue) throws Exception {
	xml = sigStartElemToWrapXml + xml + sigEndElemToWrapXml;
       Document doc = docBuilderNSTrue.parse(new InputSource(new StringReader(xml)));
       DOMStructure ds = new DOMStructure(doc.getDocumentElement().getFirstChild());
       KeyInfo keyInfo = KeyInfoFactory.getInstance().unmarshalKeyInfo(ds);
	List<?> list = keyInfo.getContent();
	for (int i = 0; i < list.size(); i++) {
		XMLStructure xmlStructure = (XMLStructure) list.get(i);
		if (xmlStructure instanceof KeyValue) {
			try {
				sigPublicKey = ((KeyValue)xmlStructure).getPublicKey();
			} catch(KeyException ke) {
				throw new KeySelectorException(ke.getMessage());
			}
			break;
		} else if (xmlStructure instanceof X509Data) {
			X509Data x509data = (X509Data)xmlStructure;
			List<?> x509datalist = x509data.getContent();
			for (int j = 0; j < x509datalist.size(); j++) {
				if (x509datalist.get(j) instanceof X509Certificate) {
					X509Certificate cert = (X509Certificate)x509datalist.get(j);
					sigPublicKey = cert.getPublicKey();
					break;
				}
			}
		}
	}
}
 
Example 9
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Recursively tries to establish chain from pool of trusted certs.
 *
 * @param certToVerify the cert that needs to be verified.
 * @param chain the chain that's being built.
 * @param certs the pool of trusted certs
 *
 * @return true if successful, false otherwise.
 */
private boolean buildChain(X509Certificate certToVerify,
                    Vector<Certificate> chain,
                    Hashtable<Principal, Vector<Certificate>> certs) {
    Principal issuer = certToVerify.getIssuerDN();
    if (isSelfSigned(certToVerify)) {
        // reached self-signed root cert;
        // no verification needed because it's trusted.
        chain.addElement(certToVerify);
        return true;
    }

    // Get the issuer's certificate(s)
    Vector<Certificate> vec = certs.get(issuer);
    if (vec == null) {
        return false;
    }

    // Try out each certificate in the vector, until we find one
    // whose public key verifies the signature of the certificate
    // in question.
    for (Enumeration<Certificate> issuerCerts = vec.elements();
         issuerCerts.hasMoreElements(); ) {
        X509Certificate issuerCert
            = (X509Certificate)issuerCerts.nextElement();
        PublicKey issuerPubKey = issuerCert.getPublicKey();
        try {
            certToVerify.verify(issuerPubKey);
        } catch (Exception e) {
            continue;
        }
        if (buildChain(issuerCert, chain, certs)) {
            chain.addElement(certToVerify);
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: Rsa.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
/**
 * 从pfx文件得到公钥
 * 
 * @param certPath
 * @param password
 * @return
 */
public static PublicKey getPublicKeyByPfxFile(String certPath, String password) {
    X509Certificate cert = getX509CertFromPfxFile(certPath, password);
    if (cert != null) {
        return cert.getPublicKey();
    } else {
        return null;
    }
}
 
Example 11
Source File: Main.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Recursively tries to establish chain from pool of trusted certs.
 *
 * @param certToVerify the cert that needs to be verified.
 * @param chain the chain that's being built.
 * @param certs the pool of trusted certs
 *
 * @return true if successful, false otherwise.
 */
private boolean buildChain(X509Certificate certToVerify,
                    Vector<Certificate> chain,
                    Hashtable<Principal, Vector<Certificate>> certs) {
    Principal issuer = certToVerify.getIssuerDN();
    if (isSelfSigned(certToVerify)) {
        // reached self-signed root cert;
        // no verification needed because it's trusted.
        chain.addElement(certToVerify);
        return true;
    }

    // Get the issuer's certificate(s)
    Vector<Certificate> vec = certs.get(issuer);
    if (vec == null) {
        return false;
    }

    // Try out each certificate in the vector, until we find one
    // whose public key verifies the signature of the certificate
    // in question.
    for (Enumeration<Certificate> issuerCerts = vec.elements();
         issuerCerts.hasMoreElements(); ) {
        X509Certificate issuerCert
            = (X509Certificate)issuerCerts.nextElement();
        PublicKey issuerPubKey = issuerCert.getPublicKey();
        try {
            certToVerify.verify(issuerPubKey);
        } catch (Exception e) {
            continue;
        }
        if (buildChain(issuerCert, chain, certs)) {
            chain.addElement(certToVerify);
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: EbicsCertificateService.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public EbicsCertificate updateCertificate(
    X509Certificate certificate, EbicsCertificate cert, boolean cleanPrivateKey)
    throws CertificateEncodingException, IOException {

  String sha = DigestUtils.sha256Hex(certificate.getEncoded());
  log.debug("sha256 HEX : {}", sha);
  log.debug("certificat : {}", new String(certificate.getEncoded()));
  log.debug("certificat size : {}", certificate.getEncoded().length);

  cert.setValidFrom(DateTool.toLocalDate(certificate.getNotBefore()));
  cert.setValidTo(DateTool.toLocalDate(certificate.getNotAfter()));
  cert.setIssuer(certificate.getIssuerDN().getName());
  cert.setSubject(certificate.getSubjectDN().getName());
  cert.setCertificate(certificate.getEncoded());
  RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
  cert.setPublicKeyExponent(publicKey.getPublicExponent().toString(16));
  cert.setPublicKeyModulus(publicKey.getModulus().toString(16));
  cert.setSerial(certificate.getSerialNumber().toString(16));
  cert.setPemString(convertToPEMString(certificate));

  if (cleanPrivateKey) {
    cert.setPrivateKey(null);
  }

  sha = sha.toUpperCase();
  cert.setSha2has(sha);
  computeFullName(cert);

  return cert;
}
 
Example 13
Source File: CertId.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a CertId. The hash algorithm used is SHA-1.
 */
public CertId(X509Certificate issuerCert, SerialNumber serialNumber)
    throws IOException {

    this(issuerCert.getSubjectX500Principal(),
         issuerCert.getPublicKey(), serialNumber);
}
 
Example 14
Source File: BuildEEBasicConstraints.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 15
Source File: CertificatePriorityComparator.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
private int compareStrength(X509Certificate lhs, X509Certificate rhs) {
    int result;
    PublicKey lhsPublicKey = lhs.getPublicKey();
    PublicKey rhsPublicKey = rhs.getPublicKey();
    result = compareKeyAlgorithm(lhsPublicKey, rhsPublicKey);
    if (result != 0) {
        return result;
    }
    result = compareKeySize(lhsPublicKey, rhsPublicKey);
    if (result != 0) {
        return result;
    }
    return compareSignatureAlgorithm(lhs, rhs);
}
 
Example 16
Source File: X509VerificationKeyResolver.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException
{
    String x5t = jws.getX509CertSha1ThumbprintHeaderValue();
    String x5tS256 = jws.getX509CertSha256ThumbprintHeaderValue();

    if (x5t == null && x5tS256 == null)
    {
        if (tryAllOnNoThumbHeader)
        {
            return attemptAll(jws);
        }
        throw new UnresolvableKeyException("Neither the " + X509_CERTIFICATE_THUMBPRINT + " header nor the " + X509_CERTIFICATE_SHA256_THUMBPRINT + " header are present in the JWS.");
    }

    X509Certificate x509Certificate = x5tMap.get(x5t);
    if (x509Certificate == null)
    {
        x509Certificate = x5tS256Map.get(x5tS256);
    }

    if (x509Certificate == null)
    {
        StringBuilder sb = new StringBuilder();

        sb.append("The X.509 Certificate Thumbprint header(s) in the JWS do not identify any of the provided Certificates -");
        if (x5t != null)
        {
            sb.append(" ").append(X509_CERTIFICATE_THUMBPRINT).append("=").append(x5t);
            sb.append(" vs. SHA-1 thumbs:").append(x5tMap.keySet());
        }

        if (x5tS256 != null)
        {
            sb.append(" ").append(X509_CERTIFICATE_SHA256_THUMBPRINT).append("=").append(x5tS256);
            sb.append(" vs. SHA-256 thumbs:").append(x5tS256Map.keySet());
        }

        sb.append(".");
        throw new UnresolvableKeyException(sb.toString());
    }

    return x509Certificate.getPublicKey();
}
 
Example 17
Source File: MTLSService.java    From oxAuth with MIT License 4 votes vote down vote up
public boolean processMTLS(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain, Client client) throws Exception {
    log.debug("Trying to authenticate client {} via {} ...", client.getClientId(),
            client.getAuthenticationMethod());

    final String clientCertAsPem = httpRequest.getHeader("X-ClientCert");
    if (StringUtils.isBlank(clientCertAsPem)) {
        log.debug("Client certificate is missed in `X-ClientCert` header, client_id: {}.", client.getClientId());
        return false;
    }

    X509Certificate cert = CertUtils.x509CertificateFromPem(clientCertAsPem);
    if (cert == null) {
        log.debug("Failed to parse client certificate, client_id: {}.", client.getClientId());
        return false;
    }
    final String cn = CertUtils.getCN(cert);
    if (!cn.equals(client.getClientId())) {
        log.error("Client certificate CN does not match clientId. Reject call, CN: " + cn + ", clientId: " + client.getClientId());
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity(errorResponseFactory.getErrorAsJson(TokenErrorResponseType.INVALID_CLIENT, httpRequest.getParameter("state"), "")).build());
    }

    if (client.getAuthenticationMethod() == AuthenticationMethod.TLS_CLIENT_AUTH) {

        final String subjectDn = client.getAttributes().getTlsClientAuthSubjectDn();
        if (StringUtils.isBlank(subjectDn)) {
            log.debug(
                    "SubjectDN is not set for client {} which is required to authenticate it via `tls_client_auth`.",
                    client.getClientId());
            return false;
        }

        // we check only `subjectDn`, the PKI certificate validation is performed by
        // apache/httpd
        if (subjectDn.equals(cert.getSubjectDN().getName())) {
            log.debug("Client {} authenticated via `tls_client_auth`.", client.getClientId());
            authenticatedSuccessfully(client, httpRequest);

            filterChain.doFilter(httpRequest, httpResponse);
            return true;
        }
    }

    if (client.getAuthenticationMethod() == AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH) { // disable it
        final PublicKey publicKey = cert.getPublicKey();
        final byte[] encodedKey = publicKey.getEncoded();

        JSONObject jsonWebKeys = Strings.isNullOrEmpty(client.getJwks())
                ? JwtUtil.getJSONWebKeys(client.getJwksUri())
                : new JSONObject(client.getJwks());

        if (jsonWebKeys == null) {
            log.debug("Unable to load json web keys for client: {}, jwks_uri: {}, jks: {}", client.getClientId(),
                    client.getJwksUri(), client.getJwks());
            return false;
        }

        final JSONWebKeySet keySet = JSONWebKeySet.fromJSONObject(jsonWebKeys);
        for (JSONWebKey key : keySet.getKeys()) {
            if (ArrayUtils.isEquals(encodedKey,
                    cryptoProvider.getPublicKey(key.getKid(), jsonWebKeys, null).getEncoded())) {
                log.debug("Client {} authenticated via `self_signed_tls_client_auth`, matched kid: {}.",
                        client.getClientId(), key.getKid());
                authenticatedSuccessfully(client, httpRequest);

                filterChain.doFilter(httpRequest, httpResponse);
                return true;
            }
        }
    }
    return false;
}
 
Example 18
Source File: U2FAttestationStatment.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
    public Boolean verifySignature(String browserDataBase64, FIDO2AuthenticatorData authData) {
        ECKeyObject ecKeyObj = null;

        List<X509Certificate> certchain = new ArrayList<>();

        try {
            if(!Arrays.equals(authData.getAttCredData().getAaguid(), new byte[16])){
                skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                        "u2f AAGUID is not zero");
                return false;
            }
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    x5c.size());
            Iterator x5cItr = x5c.iterator();
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

            byte[] certByte = (byte[]) x5cItr.next();
            InputStream instr = new ByteArrayInputStream(certByte);
            X509Certificate attCert = (X509Certificate) certFactory.generateCertificate(instr);

            PublicKey certPublicKey = attCert.getPublicKey();
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    certPublicKey.getAlgorithm());
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    "Signed Bytes Input: " + browserDataBase64);
            if (authData.getAttCredData().getFko() instanceof ECKeyObject) {
                ecKeyObj = (ECKeyObject) authData.getAttCredData().getFko();
            }
            byte[] signedBytes = Bytes.concat(new byte[]{0}, authData.getRpIdHash(), skfsCommon.getDigestBytes(Base64.getDecoder().decode(browserDataBase64), "SHA256"), authData.getAttCredData().getCredentialId(),
                    new byte[]{0x04}, ecKeyObj.getX(), ecKeyObj.getY());

            Signature ecdsaSignature = Signature.getInstance("SHA256withECDSA", "BCFIPS");
            ecdsaSignature.initVerify(certPublicKey);
            ecdsaSignature.update(signedBytes);
            return ecdsaSignature.verify(signature);
//        return Boolean.FALSE;
        } catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException | UnsupportedEncodingException | InvalidKeyException | SignatureException ex) {
            Logger.getLogger(U2FAttestationStatment.class.getName()).log(Level.SEVERE, null, ex);
        }
        return Boolean.FALSE;
    }
 
Example 19
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public X509CredentialImpl(X509Certificate cert) {
    publicKey = cert.getPublicKey();
    signingCert = cert;
}
 
Example 20
Source File: X509CredentialImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public X509CredentialImpl(X509Certificate cert) {
    publicKey = cert.getPublicKey();
    signingCert = cert;
}