Example usage for java.security.cert CertificateParsingException getMessage

List of usage examples for java.security.cert CertificateParsingException getMessage

Introduction

In this page you can find the example usage for java.security.cert CertificateParsingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:eu.europa.esig.dss.DSSASN1Utils.java

/**
 * Indicates that a X509Certificates corresponding private key is used by an authority to sign OCSP-Responses.<br>
 * http://www.ietf.org/rfc/rfc3280.txt <br>
 * http://tools.ietf.org/pdf/rfc6960.pdf 4.2.2.2<br>
 * {iso(1) identified-organization(3) dod(6) internet(1) security(5) mechanisms(5) pkix(7) keyPurpose(3)
 * ocspSigning(9)}<br>/* w ww. j  a v  a2s  .  co m*/
 * OID: 1.3.6.1.5.5.7.3.9
 *
 * @return
 */
public static boolean isOCSPSigning(CertificateToken certToken) {
    try {
        List<String> keyPurposes = certToken.getCertificate().getExtendedKeyUsage();
        if ((keyPurposes != null) && keyPurposes.contains(OID.id_kp_OCSPSigning.getId())) {
            return true;
        }
    } catch (CertificateParsingException e) {
        LOG.warn(e.getMessage());
    }
    // Responder's certificate not valid for signing OCSP responses.
    return false;
}

From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java

@Override
public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse,
        long currentTimeInMillis) throws U2FException {
    Log.info(">> processRegistrationResponse");

    String sessionId = registrationResponse.getSessionId();
    String clientDataBase64 = registrationResponse.getClientData();
    String rawRegistrationDataBase64 = registrationResponse.getRegistrationData();

    Log.info(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64);
    EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId);

    if (sessionData == null) {
        throw new U2FException("Unknown session_id");
    }/*  w w  w .  ja v a 2 s  . c om*/

    String appId = sessionData.getAppId();
    String clientData = new String(Base64.decodeBase64(clientDataBase64));
    byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64);
    Log.info("-- Input --");
    Log.info("  sessionId: " + sessionId);
    Log.info("  challenge: " + Hex.encodeHexString(sessionData.getChallenge()));
    Log.info("  accountName: " + sessionData.getAccountName());
    Log.info("  clientData: " + clientData);
    Log.info("  rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData));

    RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData);

    byte[] userPublicKey = registerResponse.getUserPublicKey();
    byte[] keyHandle = registerResponse.getKeyHandle();
    X509Certificate attestationCertificate = registerResponse.getAttestationCertificate();
    byte[] signature = registerResponse.getSignature();
    List<Transports> transports = null;
    try {
        transports = U2fAttestation.Parse(attestationCertificate).getTransports();
    } catch (CertificateParsingException e) {
        Log.warning("Could not parse transports extension " + e.getMessage());
    }

    Log.info("-- Parsed rawRegistrationResponse --");
    Log.info("  userPublicKey: " + Hex.encodeHexString(userPublicKey));
    Log.info("  keyHandle: " + Hex.encodeHexString(keyHandle));
    Log.info("  attestationCertificate: " + attestationCertificate.toString());
    Log.info("  transports: " + transports);
    try {
        Log.info("  attestationCertificate bytes: " + Hex.encodeHexString(attestationCertificate.getEncoded()));
    } catch (CertificateEncodingException e) {
        throw new U2FException("Cannot encode certificate", e);
    }
    Log.info("  signature: " + Hex.encodeHexString(signature));

    byte[] appIdSha256 = crypto.computeSha256(appId.getBytes());
    byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes());
    byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle,
            userPublicKey);

    Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates();
    if (!trustedCertificates.contains(attestationCertificate)) {
        Log.warning("attestion cert is not trusted");
    }

    verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData);

    Log.info("Verifying signature of bytes " + Hex.encodeHexString(signedBytes));
    if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) {
        throw new U2FException("Signature is invalid");
    }

    // The first time we create the SecurityKeyData, we set the counter value to 0.
    // We don't actually know what the counter value of the real device is - but it will
    // be something bigger (or equal) to 0, so subsequent signatures will check out ok.
    SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle,
            userPublicKey, attestationCertificate, /* initial counter value */ 0);
    dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData);

    Log.info("<< processRegistrationResponse");
    return securityKeyData;
}

From source file:com.tremolosecurity.unison.google.u2f.U2FServerUnison.java

@Override
public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse,
        long currentTimeInMillis) throws U2FException {
    log.debug(">> processRegistrationResponse");

    String sessionId = registrationResponse.getSessionId();
    String clientDataBase64 = registrationResponse.getClientData();
    String rawRegistrationDataBase64 = registrationResponse.getRegistrationData();

    log.debug(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64);
    EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId);

    if (sessionData == null) {
        throw new U2FException("Unknown session_id");
    }// w  w w  .j av a 2s  . c o m

    String appId = sessionData.getAppId();
    String clientData = new String(Base64.decodeBase64(clientDataBase64));
    byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64);
    if (log.isDebugEnabled()) {
        log.debug("-- Input --");
        log.debug("  sessionId: " + sessionId);
        log.debug("  challenge: " + Hex.encodeHexString(sessionData.getChallenge()));
        log.debug("  accountName: " + sessionData.getAccountName());
        log.debug("  clientData: " + clientData);
        log.debug("  rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData));
    }
    RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData);

    byte[] userPublicKey = registerResponse.getUserPublicKey();
    byte[] keyHandle = registerResponse.getKeyHandle();
    X509Certificate attestationCertificate = registerResponse.getAttestationCertificate();
    byte[] signature = registerResponse.getSignature();
    List<Transports> transports = null;
    try {
        transports = U2fAttestation.Parse(attestationCertificate).getTransports();
    } catch (CertificateParsingException e) {
        log.warn("Could not parse transports extension " + e.getMessage());
    }

    if (log.isDebugEnabled()) {
        log.debug("-- Parsed rawRegistrationResponse --");
        log.debug("  userPublicKey: " + Hex.encodeHexString(userPublicKey));
        log.debug("  keyHandle: " + Hex.encodeHexString(keyHandle));
        log.debug("  attestationCertificate: " + attestationCertificate.toString());
        log.debug("  transports: " + transports);
        try {
            log.debug("  attestationCertificate bytes: "
                    + Hex.encodeHexString(attestationCertificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            throw new U2FException("Cannot encode certificate", e);
        }
        log.debug("  signature: " + Hex.encodeHexString(signature));
    }

    byte[] appIdSha256 = crypto.computeSha256(appId.getBytes());
    byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes());
    byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle,
            userPublicKey);

    Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates();
    boolean found = false;
    for (X509Certificate trusted : trustedCertificates) {
        try {
            attestationCertificate.verify(trusted.getPublicKey());
            found = true;
        } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                | SignatureException e) {

        }
    }

    if (!found) {
        if (!this.requireAttestation) {
            log.warn("attestion cert is not trusted");
        } else {
            throw new U2FException("Attestation certificate is not trusted");
        }
    }

    verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData);
    if (log.isDebugEnabled()) {
        log.debug("Verifying signature of bytes " + Hex.encodeHexString(signedBytes));
    }

    if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) {
        throw new U2FException("Signature is invalid");
    }

    // The first time we create the SecurityKeyData, we set the counter value to 0.
    // We don't actually know what the counter value of the real device is - but it will
    // be something bigger (or equal) to 0, so subsequent signatures will check out ok.
    SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle,
            userPublicKey, attestationCertificate, /* initial counter value */ 0);
    dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData);

    if (log.isDebugEnabled()) {
        log.debug("<< processRegistrationResponse");
    }

    return securityKeyData;
}

From source file:eu.europa.esig.dss.x509.CertificateToken.java

/**
 * Indicates that a X509Certificates corresponding private key is used by an authority to sign OCSP-Responses.<br>
 * http://www.ietf.org/rfc/rfc3280.txt <br>
 * http://tools.ietf.org/pdf/rfc6960.pdf 4.2.2.2<br>
 * {iso(1) identified-organization(3) dod(6) internet(1) security(5) mechanisms(5) pkix(7) keyPurpose(3)
 * ocspSigning(9)}<br>/*  www.j  a  va  2s  .c  o m*/
 * OID: 1.3.6.1.5.5.7.3.9
 *
 * @return
 */
public boolean isOCSPSigning() {

    try {

        List<String> keyPurposes = x509Certificate.getExtendedKeyUsage();
        if ((keyPurposes != null) && keyPurposes.contains(OID.id_kp_OCSPSigning.getId())) {

            return true;
        }
    } catch (CertificateParsingException e) {

        LOG.warn(e.getMessage());
    }
    // Responder's certificate not valid for signing OCSP responses.
    return false;
}

From source file:org.ejbca.ui.cli.ca.CaImportCACertCommand.java

@Override
public CommandResult execute(ParameterContainer parameters) {
    String caName = parameters.get(CA_NAME_KEY);
    String certificateFile = parameters.get(FILE_KEY);

    boolean initAuth = parameters.containsKey(INIT_AUTH_KEY);
    String superAdminCN = parameters.get(SUPERADMIN_CN_KEY);
    if (initAuth && StringUtils.isEmpty(superAdminCN)) {
        log.error("Error: " + INIT_AUTH_KEY
                + " flag was used, but super administrator Common Name was not defined with the "
                + SUPERADMIN_CN_KEY + " switch.");
        return CommandResult.FUNCTIONAL_FAILURE;
    }//from  w w w .  j  a  va2s . c o m
    try {
        CryptoProviderTools.installBCProviderIfNotAvailable();
        Certificate certificate;
        Collection<Certificate> certs;
        try {
            try {
                //Try to parse as PEM
                certs = CertTools.getCertsFromPEM(certificateFile, Certificate.class);
                if (certs.size() != 1) {
                    log.error("PEM file must only contain one CA certificate, this PEM file contains "
                            + certs.size() + ".");
                    return CommandResult.FUNCTIONAL_FAILURE;
                } else {
                    certificate = certs.iterator().next();
                }
            } catch (CertificateParsingException e) {
                //Try parsing as binary instead.
                try {
                    certificate = CertTools.getCertfromByteArray(
                            IOUtils.toByteArray(new FileInputStream(certificateFile)), Certificate.class);
                    certs = Arrays.asList(certificate);
                } catch (CertificateParsingException e2) {
                    log.error("Error: " + certificateFile
                            + " does not contain a certificate, either in PEM or in binary format.");
                    return CommandResult.CLI_FAILURE;
                }
            }
        } catch (FileNotFoundException e) {
            log.error("Error: " + certificateFile
                    + " was not a file, not found or could otherwise not be opened.");
            return CommandResult.CLI_FAILURE;
        } catch (IOException e) {
            log.error("Unknown IOException was caught", e);
            return CommandResult.FUNCTIONAL_FAILURE;
        }

        /* 
         * We need to check if the CA already exists to determine what to do:
         *  - If CA already exist, it might be a sub CA that is waiting for certificate from an external CA
         *  - If the CA does not already exist, we import the CA certificate as an "External CA" certificate in EJBCA, so we have the CA cert in EJBCA as a trust point
         *    getCAInfo throws an exception (CADoesntExistsException) if the CA does not exists, that is how we check if the CA exists 
         */
        CAAdminSessionRemote caAdminSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(CAAdminSessionRemote.class);
        try {
            CAInfo cainfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class)
                    .getCAInfo(getAuthenticationToken(), caName);
            if (cainfo.getStatus() == CAConstants.CA_WAITING_CERTIFICATE_RESPONSE) {
                if (initAuth) {
                    log.warn(
                            "Warning: " + INIT_AUTH_KEY + " was defined but was ignored when receiving a CSR.");
                }

                log.info("CA '" + caName
                        + "' is waiting for certificate response from external CA, importing certificate as certificate response to this CA.");
                X509ResponseMessage resp = new X509ResponseMessage();
                resp.setCertificate(certificate);
                caAdminSession.receiveResponse(getAuthenticationToken(), cainfo.getCAId(), resp, null, null);
                log.info("Received certificate response and activated CA " + caName);
            } else if (cainfo.getStatus() == CAConstants.CA_EXTERNAL) {
                if (initAuth) {
                    log.warn("Warning: " + INIT_AUTH_KEY
                            + " was defined but was ignored when updating an externally imported CA.");
                }
                // CA exists and this is assumed to be an update of the imported CA certificate
                log.info("CA '" + caName
                        + "' is an external CA created by CA certificate import. Trying to update the CA certificate chain.");
                caAdminSession.importCACertificateUpdate(getAuthenticationToken(), cainfo.getCAId(),
                        EJBTools.wrapCertCollection(certs));
                log.info("Updated certificate chain for imported external CA " + caName);
            } else {
                log.error("CA '" + caName
                        + "' already exists and is not waiting for certificate response from an external CA.");
                return CommandResult.FUNCTIONAL_FAILURE;
            }
            return CommandResult.SUCCESS;
        } catch (CADoesntExistsException e) {
            // CA does not exist, we can import the certificate
            if (initAuth) {
                String subjectdn = CertTools.getSubjectDN(certificate);
                Integer caid = Integer.valueOf(subjectdn.hashCode());
                initAuthorizationModule(getAuthenticationToken(), caid.intValue(), superAdminCN);
            }
            caAdminSession.importCACertificate(getAuthenticationToken(), caName,
                    EJBTools.wrapCertCollection(certs));
            log.info("Imported CA " + caName);
            return CommandResult.SUCCESS;
        }
    } catch (CAExistsException e) {
        log.error(e.getMessage());
    } catch (IllegalCryptoTokenException e) {
        log.error(e.getMessage());
    } catch (AuthorizationDeniedException e) {
        log.error(e.getMessage());
    } catch (AccessRuleNotFoundException e) {
        log.error(e.getMessage());
    } catch (RoleExistsException e) {
        log.error(e.getMessage());
    } catch (CertPathValidatorException e) {
        log.error(e.getMessage());
    } catch (EjbcaException e) {
        log.error(e.getMessage());
    } catch (CesecoreException e) {
        log.error(e.getMessage());
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}

From source file:org.security4java.X509SubjectAlternativeNameRetriever.java

@SuppressWarnings({ "rawtypes" })
public String getUserName(X509Certificate clientCert) {
    if (logger.isDebugEnabled()) {
        logger.debug("getUserName(X509Certificate) - start");
    }//from  w w  w . ja  va  2  s . c o  m

    String userName = null;
    if (clientCert != null) {
        boolean foundUserName = false;
        if (alternativeNameTypeValue != NOT_EXISTING_TYPE) {
            try {
                if (clientCert.getSubjectAlternativeNames() != null) {
                    Collection subjectAlternativeNames = clientCert.getSubjectAlternativeNames();
                    Iterator iter = subjectAlternativeNames.iterator();
                    /* 
                     * The method goes over collection of Subject Alternative Names.
                     * If the Subject Alternative Name type is equal to the configured
                     * predefined identity name, return the user name. 
                     */
                    while (iter.hasNext()) {
                        List subjectAlternativeName = (List) iter.next();
                        Integer type = (Integer) subjectAlternativeName.get(0);
                        if (type.intValue() == alternativeNameTypeValue) {
                            Object subjectAlternativeNameValue = subjectAlternativeName.get(1);
                            if (subjectAlternativeNameValue instanceof String) {
                                userName = (String) subjectAlternativeNameValue;
                                foundUserName = true;
                                break;
                            } else if (subjectAlternativeNameValue instanceof byte[]) {
                                byte[] subjectAlternativeNameValueBytes = (byte[]) subjectAlternativeNameValue;
                                userName = getStringFromASNDerEncodedByteArray(
                                        subjectAlternativeNameValueBytes);
                                if (userName != null) {
                                    foundUserName = true;
                                    break;
                                }
                            } else {
                                if (logger.isInfoEnabled()) {
                                    logger.info(
                                            "Can not get UserName, the subjectAlternativeName not supported ["
                                                    + subjectAlternativeNameValue + "].");
                                }
                            }
                        }
                    }
                }
            } catch (CertificateParsingException e) {
                logger.info("Can not get UserName, can not get subjectAlternativeNames from certificate ["
                        + e.getMessage() + "].");
            }

        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Can not get UserName, generalName is null");
            }
        }
        if (!foundUserName) {
            logger.info("Can not found userName as part of subjectAlternativeName ["
                    + alternativeNameConfiguration + "]. Return the whole subject.");
            userName = getSubjectDN(clientCert);
        }

    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Can not get UserName, clientCert is null");
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("getUserName(X509Certificate) - end; Ret is [" + userName + "].");
    }

    return userName;
}