Example usage for java.security SignatureException getMessage

List of usage examples for java.security SignatureException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Verifies an authentication signature.
 * /*from   w w  w  .  j a  v  a2s.  c o  m*/
 * @param toBeSigned
 * @param signatureValue
 * @param authnCertificate
 * @return
 */
public boolean verifyAuthnSignature(final byte[] toBeSigned, final byte[] signatureValue,
        final X509Certificate authnCertificate) {
    final PublicKey publicKey = authnCertificate.getPublicKey();
    boolean result;
    try {
        result = this.verifySignature(signatureValue, publicKey, toBeSigned);
    } catch (final InvalidKeyException ikex) {
        LOG.warn("invalid key: " + ikex.getMessage(), ikex);
        return false;
    } catch (final NoSuchAlgorithmException nsaex) {
        LOG.warn("no such algo: " + nsaex.getMessage(), nsaex);
        return false;
    } catch (final SignatureException sigex) {
        LOG.warn("signature error: " + sigex.getMessage(), sigex);
        return false;
    }
    return result;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#verifyFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///from  w  ww .j  av  a 2  s .c o  m
public synchronized FileSecurityResponse verifyFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#verifyFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            // read in the file signature
            byte[] sigToVerify = IOUtils.toByteArray(new FileInputStream(request.getSignedFile()));

            if (DEBUG) {
                DEBUGGER.debug("sigToVerify: {}", sigToVerify);
            }

            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initVerify(keyPair.getPublic());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            response.setIsSignatureValid(signature.verify(sigToVerify));
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.VERIFYFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#signFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///from w ww  . j  a  v a2  s  .c  om
public synchronized FileSecurityResponse signFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#signFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initSign(keyPair.getPrivate());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            byte[] sig = signature.sign();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
            }

            IOUtils.write(sig, new FileOutputStream(request.getSignedFile()));

            if ((request.getSignedFile().exists()) && (request.getSignedFile().length() != 0)) {
                response.setSignedFile(request.getSignedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.SIGNFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:com.znsx.cms.service.impl.LicenseManagerImpl.java

/**
 * License/*from w w  w .j  ava  2s. c o  m*/
 * 
 * @param license
 *            ?License
 * @throws BusinessException
 * @author huangbuji
 *         <p />
 *         Create at 2013 ?7:34:21
 */
private void contentCheck(License license) throws BusinessException {
    if (StringUtils.isBlank(license.getSignature())) {
        throw new BusinessException(ErrorCode.LICENSE_HAS_BEEN_CHANGED, "License content has been changed !");
    }
    // String publicKeyString = getPublicKey();
    byte[] publicKey = getPublicBinKey();
    boolean contentVerify = false;
    try {
        // contentVerify = LicenceUtil.verify(license.toString(),
        // publicKeyString, license.getSignature());
        contentVerify = LicenceUtil.verifyBinKey(license.toString(), publicKey, license.getSignature());
    } catch (SignatureException e) {
        e.printStackTrace();
        throw new BusinessException(ErrorCode.LICENSE_FORMAT_INVALID, "Format of license file invalid !");
    } catch (Exception e) {
        e.printStackTrace();
        throw new BusinessException(ErrorCode.ERROR, e.getMessage());
    }
    if (!contentVerify) {
        throw new BusinessException(ErrorCode.LICENSE_HAS_BEEN_CHANGED, "License content has been changed !");
    }
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Creates and sends the REST request./*from   www.  ja v  a  2  s . c om*/
 *
 * @return A string containing the TeleSign web server's Response.
 * @throws IOException
 *          A {@link java.security.SignatureException} signals that an
 *          error occurred while attempting to sign the Request.
 */
public String executeRequest() throws IOException {

    String signingString = getSigningString(customer_id);
    String signature;
    String url_output = "";

    // Create the absolute form of the resource URI, and place it in a string buffer.
    StringBuffer full_url = new StringBuffer(base).append(resource);

    if (params.size() > 0) {

        full_url.append("?");
        int i = 0;

        for (String key : params.keySet()) {

            if (++i != 0) {

                full_url.append("&");
            }

            full_url.append(URLEncoder.encode(key, "UTF-8")).append("=")
                    .append(URLEncoder.encode(params.get(key), "UTF-8"));
        }
    }

    url = new URL(full_url.toString());

    // Create the Signature using the formula: Signature = Base64(HMAC-SHA( YourTeleSignAPIKey, UTF-8-Encoding-Of( StringToSign )).
    try {

        signature = encode(signingString, secret_key);
    } catch (SignatureException e) {

        System.err.println("Error signing request " + e.getMessage());

        return null;
    }

    String auth_header = "TSA " + customer_id + ":" + signature;

    connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(connectTimeout);
    connection.setReadTimeout(readTimeout);
    connection.setRequestProperty("Authorization", auth_header);
    setTLSProtocol();

    if (post) {

        connection.setRequestProperty("Content-Length", Integer.toString(body.length()));
    }

    for (String key : ts_headers.keySet()) {

        connection.setRequestProperty(key, ts_headers.get(key));
    }

    for (String key : headers.keySet()) {

        connection.setRequestProperty(key, headers.get(key));
    }

    if (post) {

        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(body);
        wr.flush();
        wr.close();
    }

    int response = connection.getResponseCode();

    BufferedReader in;

    try {

        InputStream isr = (response == 200) ? connection.getInputStream() : connection.getErrorStream();
        in = new BufferedReader(new InputStreamReader(isr));
        String urlReturn;

        while ((urlReturn = in.readLine()) != null) {

            url_output += urlReturn;
        }

        in.close();
    } catch (IOException e) {
        System.err.println("IOException while reading from input stream " + e.getMessage());
        throw new RuntimeException(e);
    }

    return url_output;
}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

public String buildUrl(String command, Param... params) throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    String apiShared = "";
    String apiSecret = "";
    try {//from ww w  .j  a  va 2  s .c  om
        List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
        for (ContextRequirements.Field f : fields) {
            if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                byte[][] keyPair = (byte[][]) ctx.getConfigurationValue(f);
                apiShared = new String(keyPair[0], "utf-8");
                apiSecret = new String(keyPair[1], "utf-8");
            }
        }
    } catch (UnsupportedEncodingException ignore) {
    }

    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }
    try {
        StringBuilder str = new StringBuilder();
        String apiKey = apiShared;
        String accessKey = apiSecret;

        StringBuilder newKey = new StringBuilder();
        for (int i = 0; i < apiKey.length(); i++) {
            char c = apiKey.charAt(i);

            if (c != '\r') {
                newKey.append(c);
            }
        }
        apiKey = newKey.toString();
        newKey = new StringBuilder();
        for (int i = 0; i < accessKey.length(); i++) {
            char c = accessKey.charAt(i);

            if (c != '\r') {
                newKey.append(c);
            }
        }
        accessKey = newKey.toString();
        str.append(ctx.getCloud().getEndpoint());

        // Make sure the url ends up exactly as http://x.x.x.x:y/client/api?command=
        // otherwise the server may choke like we've found it does for uploadSslCert command.
        while (str.lastIndexOf("/") == str.length() - 1) {
            str.deleteCharAt(str.length() - 1);
        }
        if (!str.toString().endsWith("/api")) {
            str.append("/api");
        }
        str.append("?command=");
        str.append(command);
        for (Param param : params) {
            str.append("&");
            str.append(param.getKey());
            if (param.getValue() != null) {
                str.append("=");
                str.append(URLEncoder.encode(param.getValue(), "UTF-8").replaceAll("\\+", "%20"));
            }
        }
        str.append("&apiKey=");
        str.append(URLEncoder.encode(apiKey, "UTF-8").replaceAll("\\+", "%20"));
        str.append("&signature=");
        try {
            str.append(URLEncoder.encode(getSignature(command, apiKey, accessKey, params), "UTF-8")
                    .replaceAll("\\+", "%20"));
        } catch (SignatureException e) {
            throw new InternalException(e);
        }
        return str.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new RuntimeException("This cannot happen: " + e.getMessage());
    }
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceImpl.java

/**
 * Extract credentials from the request.
 *
 * @param req//from w ww.  j  a va  2s. c  o  m
 * @return credentials associated with the request.
 */
public Credentials getCredentials(HttpServletRequest req, HttpServletResponse response) {
    if (testing) {
        calls.add(new Object[] { "getCredentials", req, response });
        return new SimpleCredentials("testing", "testing".toCharArray());
    }
    Credentials cred = null;
    String userId = null;
    String sakaiTrustedHeader = req.getHeader("x-sakai-token");
    if (trustedTokenEnabled && sakaiTrustedHeader != null && sakaiTrustedHeader.trim().length() > 0) {
        String host = req.getRemoteAddr();
        if (!safeHostAddrSet.contains(host)) {
            LOG.warn("Ignoring Trusted Token request from {} ", host);
        } else {
            // we have a HMAC based token, we should see if it is valid against the key we
            // have
            // and if so create some credentials.
            String[] parts = sakaiTrustedHeader.split(";");
            if (parts.length == 3) {
                try {
                    String hash = parts[0];
                    String user = parts[1];
                    String timestamp = parts[2];
                    String hmac = Signature.calculateRFC2104HMAC(user + ";" + timestamp, sharedSecret);
                    if (hmac.equals(hash)) {
                        // the user is Ok, we will trust it.
                        userId = user;
                        cred = createCredentials(userId, TrustedTokenTypes.TRUSTED_TOKEN);
                    } else {
                        LOG.debug("HMAC Match Failed {} != {} ", hmac, hash);
                    }
                } catch (SignatureException e) {
                    LOG.warn("Failed to validate server token : {} {} ", sakaiTrustedHeader, e.getMessage());
                }
            } else {
                LOG.warn("Illegal number of elements in trusted server token:{} {}  ", sakaiTrustedHeader,
                        parts.length);
            }
        }
    }
    if (userId == null) {
        if (usingSession) {
            HttpSession session = req.getSession(false);
            if (session != null) {
                Credentials testCredentials = (Credentials) session.getAttribute(SA_AUTHENTICATION_CREDENTIALS);
                if (testCredentials instanceof SimpleCredentials) {
                    SimpleCredentials sc = (SimpleCredentials) testCredentials;
                    Object o = sc.getAttribute(CA_AUTHENTICATION_USER);
                    if (o instanceof TrustedUser) {
                        TrustedUser tu = (TrustedUser) o;
                        if (tu.getUser() != null) {
                            userId = tu.getUser();
                            cred = testCredentials;
                        }
                    }
                }
            } else {
                cred = null;
            }
        } else {
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (trustedAuthCookieName.equals(c.getName())) {
                        if (secureCookie && !c.getSecure()) {
                            continue;
                        }
                        String cookieValue = c.getValue();
                        String[] decodedToken = decodeCookie(c.getValue());
                        if (decodedToken != null) {
                            userId = decodedToken[0];
                            String tokenType = decodedToken[1];
                            TokenTrustValidator ttv = registeredTypes.get(tokenType);
                            if (ttv == null || ttv.isTrusted(req)) {
                                LOG.debug("Token is valid and decoded to {} ", userId);
                                cred = createCredentials(userId, tokenType);
                                refreshToken(response, c.getValue(), userId, tokenType);
                                break;
                            } else {
                                LOG.debug("Cookie cant be trusted for this request {} ", cookieValue);
                            }
                        } else {
                            LOG.debug("Invalid Cookie {} ", cookieValue);
                            clearCookie(response);
                        }
                    }
                }
            }
        }
    }
    if (userId != null) {
        LOG.debug("Trusted Authentication for {} with credentials {}  ", userId, cred);
    }

    return cred;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

/** Checks the signature on an OCSP request and checks that it is signed by an allowed CA.
 * Does not check for revocation of the signer certificate
 * //from   ww w . j  a  v a  2  s  . com
 * @param clientRemoteAddr The ip address or hostname of the remote client that sent the request, can be null.
 * @param req The signed OCSPReq
 * @param cacerts a CertificateCache of Certificates, the authorized CA-certificates. The signer certificate must be issued by one of these.
 * @return X509Certificate which is the certificate that signed the OCSP request
 * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized
 * @throws SignRequestException if there is no signature on the OCSPReq
 * @throws OCSPException if the request can not be parsed to retrieve certificates
 * @throws NoSuchProviderException if the BC provider is not installed
 * @throws CertificateException if the certificate can not be parsed
 * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm
 * @throws InvalidKeyException if the certificate, or CA key is invalid
 * @throws OperatorCreationException 
 */
public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req,
        CaCertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException,
        CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException,
        OperatorCreationException {

    X509Certificate signercert = null;

    if (!req.isSigned()) {
        String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr);
        log.info(infoMsg);
        throw new SignRequestException(infoMsg);
    }
    // Get all certificates embedded in the request (probably a certificate chain)
    X509CertificateHolder[] certs = req.getCerts();
    // Set, as a try, the signer to be the first certificate, so we have a name to log...
    String signer = null;
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    if (certs.length > 0) {
        signer = CertTools.getSubjectDN(converter.getCertificate(certs[0]));
    }

    // We must find a cert to verify the signature with...
    boolean verifyOK = false;
    for (int i = 0; i < certs.length; i++) {
        if (req.isSignatureValid(new JcaContentVerifierProviderBuilder().build(certs[i])) == true) {
            signercert = converter.getCertificate(certs[i]);
            signer = CertTools.getSubjectDN(signercert);
            Date now = new Date();
            String signerissuer = CertTools.getIssuerDN(signercert);
            String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer);
            log.info(infoMsg);
            verifyOK = true;
            // Also check that the signer certificate can be verified by one of the CA-certificates
            // that we answer for
            X509Certificate signerca = cacerts.findLatestBySubjectDN(HashID.getFromIssuerDN(certs[i]));
            String subject = signer;
            String issuer = signerissuer;
            if (signerca != null) {
                try {
                    signercert.verify(signerca.getPublicKey());
                    if (log.isDebugEnabled()) {
                        log.debug("Checking validity. Now: " + now + ", signerNotAfter: "
                                + signercert.getNotAfter());
                    }
                    CertTools.checkValidity(signercert, now);
                    // Move the error message string to the CA cert
                    subject = CertTools.getSubjectDN(signerca);
                    issuer = CertTools.getIssuerDN(signerca);
                    CertTools.checkValidity(signerca, now);
                } catch (SignatureException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                } catch (InvalidKeyException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateNotYetValidException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer,
                            e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateExpiredException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer,
                            e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                }
            } else {
                infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer);
                log.info(infoMsg);
                verifyOK = false;
            }
            break;
        }
    }
    if (!verifyOK) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer);
        log.info(errMsg);
        throw new SignRequestSignatureException(errMsg);
    }

    return signercert;
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

/**
 * Checks the signature on an OCSP request and checks that it is signed by an allowed CA. Does not check for revocation of the signer certificate
 * /*from   w  w  w .j a  v  a  2s.  c o  m*/
 * @param clientRemoteAddr The IP address or host name of the remote client that sent the request, can be null.
 * @param req The signed OCSPReq
 * @return X509Certificate which is the certificate that signed the OCSP request
 * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized
 * @throws SignRequestException if there is no signature on the OCSPReq
 * @throws OCSPException if the request can not be parsed to retrieve certificates
 * @throws NoSuchProviderException if the BC provider is not installed
 * @throws CertificateException if the certificate can not be parsed
 * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm
 * @throws InvalidKeyException if the certificate, or CA key is invalid
 */
private X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req) throws SignRequestException,
        SignRequestSignatureException, CertificateException, NoSuchAlgorithmException {

    X509Certificate signercert = null;

    if (!req.isSigned()) {
        String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr);
        log.info(infoMsg);
        throw new SignRequestException(infoMsg);
    }
    // Get all certificates embedded in the request (probably a certificate chain)
    try {
        X509Certificate[] certs = req.getCerts("BC");
        // Set, as a try, the signer to be the first certificate, so we have a name to log...
        String signer = null;
        if (certs.length > 0) {
            signer = CertTools.getSubjectDN(certs[0]);
        }

        // We must find a certificate to verify the signature with...
        boolean verifyOK = false;
        for (int i = 0; i < certs.length; i++) {
            if (req.verify(certs[i].getPublicKey(), "BC") == true) {
                signercert = certs[i];
                signer = CertTools.getSubjectDN(signercert);
                Date now = new Date();
                String signerissuer = CertTools.getIssuerDN(signercert);
                String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer);
                log.info(infoMsg);
                verifyOK = true;
                /*
                 * Also check that the signer certificate can be verified by one of the CA-certificates that we answer for
                 */

                X509Certificate signerca = certificateStoreSession
                        .findLatestX509CertificateBySubject(CertTools.getIssuerDN(certs[i]));
                String subject = signer;
                String issuer = signerissuer;
                if (signerca != null) {
                    try {
                        signercert.verify(signerca.getPublicKey());
                        if (log.isDebugEnabled()) {
                            log.debug("Checking validity. Now: " + now + ", signerNotAfter: "
                                    + signercert.getNotAfter());
                        }
                        CertTools.checkValidity(signercert, now);
                        // Move the error message string to the CA cert
                        subject = CertTools.getSubjectDN(signerca);
                        issuer = CertTools.getIssuerDN(signerca);
                        CertTools.checkValidity(signerca, now);
                    } catch (SignatureException e) {
                        infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                                issuer, e.getMessage());
                        log.info(infoMsg);
                        verifyOK = false;
                    } catch (InvalidKeyException e) {
                        infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                                issuer, e.getMessage());
                        log.info(infoMsg);
                        verifyOK = false;
                    } catch (CertificateNotYetValidException e) {
                        infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer,
                                e.getMessage());
                        log.info(infoMsg);
                        verifyOK = false;
                    } catch (CertificateExpiredException e) {
                        infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer,
                                e.getMessage());
                        log.info(infoMsg);
                        verifyOK = false;
                    }
                } else {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer);
                    log.info(infoMsg);
                    verifyOK = false;
                }
                break;
            }
        }
        if (!verifyOK) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer);
            log.info(errMsg);
            throw new SignRequestSignatureException(errMsg);
        }
    } catch (OCSPException e) {
        throw new CryptoProviderException("BouncyCastle was not initialized properly.", e);
    } catch (NoSuchProviderException e) {
        throw new CryptoProviderException("BouncyCastle was not found as a provider.", e);
    }

    return signercert;
}

From source file:com.netscape.cmscore.apps.CMSEngine.java

/**
 * sign some known data to determine if signing key is botched;
 * if so, proceed to graceful shutdown//from w w  w.  ja  v  a 2  s .c  om
 */
public void checkForAndAutoShutdown() {
    String method = "CMSEngine: checkForAndAutoShutdown: ";
    logger.debug(method + "begins");

    try {
        boolean allowShutdown = mConfig.getBoolean("autoShutdown.allowed", false);
        if ((!allowShutdown) || (mSigningKey == null) || (mSigningData == null)) {
            logger.debug(method + "autoShutdown not allowed");
            return;
        }
        logger.debug(method + "autoShutdown allowed");
        CryptoToken token = ((org.mozilla.jss.pkcs11.PK11PrivKey) mSigningKey).getOwningToken();
        SignatureAlgorithm signAlg = Cert.mapAlgorithmToJss("SHA256withRSA");
        Signature signer = token.getSignatureContext(signAlg);

        signer.initSign(mSigningKey);
        signer.update(mSigningData);
        byte[] result = signer.sign();
        logger.debug(method + " signining successful: " + new String(result));
    } catch (SignatureException e) {

        //Let's write to the error console in case we are in a bad memory situation
        //This will be the most likely to work, giving us a record of the signing failure
        ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_CA_SIGNING_OPERATION_FAILED", e.toString())));

        logger.warn(method + "autoShutdown for " + e.getMessage(), e);

        autoShutdown();
    } catch (Exception e) {
        logger.warn(method + "continue for " + e.getMessage(), e);
    }
    logger.debug(method + "passed; continue");
}