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:org.ejbca.core.protocol.ocsp.OCSPUtil.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.  ja  v a  2 s .c  om*/
 * @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
 */
public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req,
        ICertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException,
        CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException {

    X509Certificate signercert = null;

    if (!req.isSigned()) {
        String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr);
        m_log.info(infoMsg);
        throw new SignRequestException(infoMsg);
    }
    // Get all certificates embedded in the request (probably a certificate chain)
    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 cert 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);
            m_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 (m_log.isDebugEnabled()) {
                        m_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());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (InvalidKeyException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateNotYetValidException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer,
                            e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateExpiredException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer,
                            e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                }
            } else {
                infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer);
                m_log.info(infoMsg);
                verifyOK = false;
            }
            break;
        }
    }
    if (!verifyOK) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer);
        m_log.info(errMsg);
        throw new SignRequestSignatureException(errMsg);
    }

    return signercert;
}

From source file:tkwatch.Utilities.java

/**
 * Issues a TradeKing API request. Adapted from the <i>TradeKing API
 * Reference Guide</i>, 03.25.2011, p. 51.
 * //from   w w  w.  jav  a  2s  .  c o  m
 * @param resourceUrl
 *            The URL to which API requests must be made.
 * @param body
 *            The body of the API request.
 * @param appKey
 *            The user's application key.
 * @param userKey
 *            The user's key.
 * @param userSecret
 *            The user's secret key.
 * @return Returns the result of the API request.
 */
public static final String tradeKingRequest(final String resourceUrl, final String body, final String appKey,
        final String userKey, final String userSecret) {
    String response = new String();
    try {
        String timestamp = String.valueOf(Calendar.getInstance().getTimeInMillis());
        String request_data = body + timestamp;
        String signature = generateSignature(request_data, userSecret);
        URL url = new URL(resourceUrl);
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Accept", "application/xml");
        conn.setRequestProperty("TKI_TIMESTAMP", timestamp);
        conn.setRequestProperty("TKI_SIGNATURE", signature);
        conn.setRequestProperty("TKI_USERKEY", userKey);
        conn.setRequestProperty("TKI_APPKEY", appKey);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(body);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        in.close();
        return response;
    } catch (java.security.SignatureException e) {
        errorMessage(e.getMessage());
        return "";
    } catch (java.io.IOException e) {
        errorMessage(e.getMessage());
        return "";
    }
}

From source file:hudson.util.SignatureOutputStream.java

@Override
public void write(int b) throws IOException {
    try {//from ww  w. j a  v  a2 s  . co  m
        sig.update((byte) b);
        out.write(b);
    } catch (SignatureException e) {
        throw (IOException) new IOException(e.getMessage()).initCause(e);
    }
}

From source file:hudson.util.SignatureOutputStream.java

@Override
public void write(byte[] b, int off, int len) throws IOException {
    try {/*  w  w w .  j a  va 2  s.c o m*/
        sig.update(b, off, len);
        out.write(b, off, len);
    } catch (SignatureException e) {
        throw (IOException) new IOException(e.getMessage()).initCause(e);
    }
}

From source file:com.premiumminds.billy.portugal.services.certification.CertificationManager.java

public boolean verifyHashBinary(String source, byte[] hash) throws InvalidKeyException {
    try {//w  w w.  ja v  a2s  .  c o  m
        this.signature.initVerify(this.publicKey);
        this.signature.update(source.getBytes());
        return this.signature.verify(hash);
    } catch (SignatureException e) {
        CertificationManager.log.error(e.getMessage(), e);
    }
    return false;
}

From source file:org.sakaiproject.nakamura.messagebucket.UntrustedMessageBucketServiceImpl.java

public String getToken(String userId, String context) throws MessageBucketException {
    try {//from   w  ww .  jav  a  2 s.c om
        String timeStamp = Long.toHexString(System.currentTimeMillis());
        String hmac = Signature.calculateRFC2104HMAC(userId + ";" + timeStamp + ";" + context, sharedSecret);
        String token = userId + ";" + timeStamp + ";" + context + ";" + hmac;
        return Base64.encodeBase64URLSafeString(token.getBytes("UTF8"));
    } catch (SignatureException e) {
        throw new MessageBucketException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new MessageBucketException(e.getMessage(), e);
    }
}

From source file:com.teasoft.teavote.controller.BackupController.java

@ExceptionHandler(SignatureException.class)
@ResponseBody//  www .ja  v  a 2  s . c om
public JSONResponse signatureException(SignatureException e) {
    return new JSONResponse(false, 0, null, e.getMessage());
}

From source file:org.nimbustools.ctxbroker.security.DefaultBootstrapFactory.java

public BootstrapInformation newBootstrap(String uuid, String ctxServiceURL, Calendar expires)
        throws ContextBrokerException {

    BootstrapInformation bootstrap = new BootstrapInformation();

    KeyPair keypair = this.ca.createNewKeyPair();

    X509Certificate cert;/*  www.  j av a 2s  .  c  o  m*/
    try {
        cert = this.ca.signNewCertificate(uuid, keypair.getPublic(), expires);
    } catch (SignatureException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    }

    try {
        bootstrap.setX509Cert(cert);
    } catch (CertificateEncodingException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    }
    try {
        bootstrap.setKeypair(keypair);
    } catch (IOException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    }

    X500Principal subjectDN = cert.getSubjectX500Principal();
    String DN = subjectDN.getName(X500Principal.RFC2253);
    String globusDN = CertUtil.toGlobusID(DN, false);
    bootstrap.setBootstrapDN(globusDN);

    return bootstrap;
}

From source file:com.idevity.card.read.ShowCHUID.java

/**
 * Method onCreateView./*from   w ww.j a  va  2s. c  o m*/
 * 
 * @param inflater
 *            LayoutInflater
 * @param container
 *            ViewGroup
 * @param savedInstanceState
 *            Bundle
 * @return View
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Globals g = Globals.getInstance();
    String issuer = new String();
    String subject = new String();
    String validfrom = new String();
    String validto = new String();
    boolean certvalid = true;
    boolean sigvalid = false;
    CMSSignedDataObject chuidSig = null;
    X509Certificate pcs = null;

    View chuidLayout = inflater.inflate(R.layout.activity_show_chuid, container, false);
    // get card data

    byte[] _data = g.getCard();
    CardData80073 carddata = new CardData80073(_data);

    // get chuid
    PIVCardHolderUniqueID chuid = null;
    PIVDataTempl chuidInDataTempl = carddata.getPIVCardHolderUniqueID();
    if (chuidInDataTempl != null) {
        byte[] chuidData = chuidInDataTempl.getData();
        if (chuidData == null) {
            chuidData = chuidInDataTempl.getEncoded();
        }
        chuid = new PIVCardHolderUniqueID(chuidData);
    }
    if (chuid != null) {
        try {
            // get chuid signature object
            chuidSig = new CMSSignedDataObject(chuid.getSignatureBytes(), chuid.getSignatureDataBytes());
            chuidSig.setProviderName("OpenSSLFIPSProvider");
            // validate the signature, don't do PDVAL
            sigvalid = chuidSig.verifySignature(false);
        } catch (SignatureException e) {
            Log.e(TAG, "Error: " + e.getMessage());
        }
        // get x509 cert
        if (chuidSig != null) {
            pcs = chuidSig.getSigner();
        }
        // get values from x509
        if (pcs != null) {
            issuer = pcs.getIssuerDN().getName();
            subject = pcs.getSubjectDN().getName();
            validfrom = pcs.getNotBefore().toString();
            validto = pcs.getNotAfter().toString();
        }

    }

    ImageView sigthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator1);
    TextView sigtext = (TextView) chuidLayout.findViewById(R.id.chuid1);
    if (sigvalid) {
        sigthumbs.setImageResource(R.drawable.cert_good);
    } else {
        sigthumbs.setImageResource(R.drawable.cert_bad);
        sigtext.setTextColor(getResources().getColor(R.color.idredmain));
    }

    /*
     * Note to self. I am not thrilled how Java almost forces you to assume
     * a certificate if valid unless an exception is thrown!
     */
    TextView vfText = (TextView) chuidLayout.findViewById(R.id.chuid4);
    TextView vtText = (TextView) chuidLayout.findViewById(R.id.chuid5);

    try {
        if (pcs != null) {
            pcs.checkValidity();
        }
    } catch (CertificateNotYetValidException e) {
        certvalid = false;
        vfText.setTextColor(getResources().getColor(R.color.idredmain));
        if (debug) {
            Log.d(TAG, "Error: Authentication Certificate Not Vaid Yet!");
        }
    } catch (CertificateExpiredException e) {
        certvalid = false;
        vtText.setTextColor(getResources().getColor(R.color.idredmain));
        if (debug) {
            Log.d(TAG, "Error: Card Authentication Certificate Expired!");
        }
    }
    ImageView certthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator2);
    TextView certtext = (TextView) chuidLayout.findViewById(R.id.chuid2);
    if (certvalid && pcs != null) {
        certthumbs.setImageResource(R.drawable.cert_good);
    } else {
        certthumbs.setImageResource(R.drawable.cert_bad);
        certtext.setTextColor(getResources().getColor(R.color.idredmain));
    }

    // setting all values in activity
    TextView editChuidSubject = (TextView) chuidLayout.findViewById(R.id.chuid_subject);
    editChuidSubject.setText(subject);

    TextView editValidFrom = (TextView) chuidLayout.findViewById(R.id.chuid_date);
    editValidFrom.setText(validfrom);

    TextView editValidTo = (TextView) chuidLayout.findViewById(R.id.chuid_expiry);
    editValidTo.setText(validto);

    TextView editIssuer = (TextView) chuidLayout.findViewById(R.id.chuid_issuer);
    editIssuer.setText(issuer);

    return chuidLayout;
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 * @param cert/* w ww  .ja va2s  .  com*/
 * @return true when the certificate is self signed
 */
public static boolean isCertificateSelfSigned(X509Certificate cert) {
    try {
        PublicKey publicKey = cert.getPublicKey();
        cert.verify(publicKey);
        return true;
    } catch (java.security.SignatureException sigEx) {
        LOG.info("ERROR : SignatureException {}", sigEx.getMessage());
        LOG.debug("ERROR : SignatureException {}", sigEx);
        return false;
    } catch (InvalidKeyException keyEx) {
        // Invalid key --> not self-signed
        LOG.info("ERROR : InvalidKeyException {}", keyEx.getMessage());
        LOG.debug("ERROR : InvalidKeyException {}", keyEx);
        return false;
    } catch (CertificateException certExc) {
        LOG.info("ERROR : CertificateException {}", certExc.getMessage());
        LOG.debug("ERROR : CertificateException {}", certExc);
        return false;
    } catch (NoSuchAlgorithmException nsaExc) {
        LOG.info("ERROR : Bad algorithm: " + nsaExc.getMessage());
        LOG.debug("ERROR : Bad algorithm: " + nsaExc);
        return false;
    } catch (NoSuchProviderException nspExc) {
        LOG.info("ERROR : Bad provider: " + nspExc.getMessage());
        LOG.debug("ERROR : Bad provider: " + nspExc);
        return false;
    }
}