Example usage for java.security SignatureException SignatureException

List of usage examples for java.security SignatureException SignatureException

Introduction

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

Prototype

public SignatureException(Throwable cause) 

Source Link

Document

Creates a SignatureException with the specified cause and a detail message of (cause==null ?

Usage

From source file:ai.susi.tools.JsonSignature.java

/**
 * Verfies if the signature of a JSONObject is valid
 * @param obj the JSONObject/*from  ww w .  j  ava2s. c  om*/
 * @param key the public key of the signature issuer
 * @return true if the signature is valid
 * @throws SignatureException if the JSONObject does not have a signature or something with the JSONObject is bogus
 * @throws InvalidKeyException if the key is not valid (for example not RSA)
 */
public static boolean verify(JSONObject obj, PublicKey key) throws SignatureException, InvalidKeyException {

    if (!obj.has(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    String sigString = obj.getString(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:org.innobuilt.fincayra.fps.SignatureUtils.java

/**
 * Calculate String to Sign // w  w  w .  j  ava  2  s  .c  o  m
 * 
 * @param parameters
 * @param httpMethod
 *            - POST or GET
 * @param hostHeader
 *            - Service end point
 * @param requestURI
 *            - Path
 * @return
 * @throws SignatureException
 */
public static String calculateStringToSignV2(Map<String, String> parameters, String httpMethod,
        String hostHeader, String requestURI) throws SignatureException {
    StringBuffer stringToSign = new StringBuffer("");
    if (httpMethod == null)
        throw new SignatureException("HttpMethod cannot be null");
    stringToSign.append(httpMethod);
    stringToSign.append(NewLine);

    // The host header - must eventually convert to lower case
    // Host header should not be null, but in Http 1.0, it can be, in that
    // case just append empty string ""
    if (hostHeader == null)
        stringToSign.append("");
    else
        stringToSign.append(hostHeader.toLowerCase());
    stringToSign.append(NewLine);

    if (requestURI == null || requestURI.length() == 0)
        stringToSign.append(EmptyUriPath);
    else
        stringToSign.append(v2UrlEncode(requestURI, true));
    stringToSign.append(NewLine);

    Map<String, String> sortedParamMap = new TreeMap<String, String>();
    sortedParamMap.putAll(parameters);
    Iterator<Map.Entry<String, String>> pairs = sortedParamMap.entrySet().iterator();
    while (pairs.hasNext()) {
        Map.Entry<String, String> pair = pairs.next();
        if (pair.getKey().equalsIgnoreCase(SIGNATURE_KEYNAME))
            continue;
        stringToSign.append(v2UrlEncode(pair.getKey(), false));
        stringToSign.append(Equals);
        stringToSign.append(v2UrlEncode(pair.getValue(), false));
        if (pairs.hasNext())
            stringToSign.append(And);
    }
    return stringToSign.toString();
}

From source file:edu.wfu.inotado.helper.EncryptionHelper.java

public String calculateHMAC(String data, String key) throws java.security.SignatureException {
    String result = "";
    try {//from   ww  w.j  ava 2 s .  co m

        if (!StringUtils.isBlank(data) && !StringUtils.isBlank(key)) {
            // get an hmac_sha1 key from the raw key bytes
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

            // get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);

            // compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(data.getBytes());

            // base64-encode the hmac
            result = new String(Base64.encodeBase64(rawHmac));
        } else {
            log.warn("data or key appears to be empty!");
        }
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:net.oauth.signatures.SignedOAuthTokenParser.java

/**
 * Extracts the signed OAuth token from the Authorization header and then verifies it.
 * @param request the {@link HttpServletRequest} that contains the signed OAuth token in the
 *   Authorization header./*from  w  ww.j av a 2 s .co m*/
 * @return the signed OAuth token.
 * @throws SignatureException if the signature doesn't check out, or if authentication fails
 *   for other reason (missing Authorization header, etc.).
 */
public SignedOAuthToken parseToken(HttpServletRequest request) throws SignatureException {

    // this guaranteed to return a string starting with "Token", or null
    String header = getAuthHeader(request);

    if (header == null) {
        throw new SignatureException("missing Authorization header of type 'Token'");
    }

    String postFix = header.substring(0, SignedOAuthToken.AUTH_METHOD.length()); // read past "Token"
    NameValuePair nvp = BasicHeaderValueParser.parseNameValuePair(postFix.trim(), null);

    if (nvp == null) {
        throw new SignatureException("missing signed_token in Authorization header: " + header);
    }

    if (!SignedOAuthToken.SIGNED_TOKEN_PARAM.equals(nvp.getName())) {
        // Not logging the header in this case. maybe they just mis-spelled "token", but did send the
        // actual OAuth token. We don't want to log that.
        throw new SignatureException("missing signed_token in Authorization header");
    }

    String token = nvp.getValue().trim();

    String method = request.getMethod();

    StringBuffer uri = request.getRequestURL();

    if (request.getQueryString() != null) {
        uri.append("?");
        uri.append(request.getQueryString());
    }

    return parseToken(token, method, uri.toString());
}

From source file:ai.susi.tools.JsonSignature.java

public static boolean verify(Map<String, byte[]> obj, PublicKey key)
        throws SignatureException, InvalidKeyException {

    if (!obj.containsKey(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;/*from   w  ww .j ava 2 s. co m*/
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    byte[] sigString = obj.get(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:org.carewebframework.api.security.DigitalSignature.java

/**
 * @see org.carewebframework.api.security.IDigitalSignature#sign(java.lang.String)
 *//*from  ww w . j  a v a 2  s .c  o  m*/
@Override
public String sign(String content) throws Exception {
    PrivateKey privateKey = (PrivateKey) keystore.getKey(keyName, privateKeyPassword.toCharArray());

    if (privateKey == null) {
        throw new SignatureException("No key " + keyName + " found");
    }

    return CipherUtil.sign(privateKey, content);
}

From source file:be.fedict.commons.eid.jca.BeIDPrivateKey.java

byte[] sign(final byte[] digestValue, final String digestAlgo) throws SignatureException {
    LOG.debug("auto recovery: " + this.autoRecovery);
    final BeIDDigest beIDDigest = beIDDigests.get(digestAlgo);
    if (null == beIDDigest) {
        throw new SignatureException("unsupported algo: " + digestAlgo);
    }//w w w  .  j a  v a2 s  .c o  m
    byte[] signatureValue;
    try {
        if (this.autoRecovery) {
            /*
             * We keep a copy of the authentication certificate to make sure
             * that the automatic recovery only operates against the same
             * eID card.
             */
            if (null == this.authenticationCertificate) {
                try {
                    this.authenticationCertificate = this.beIDCard.getAuthenticationCertificate();
                } catch (Exception e) {
                    // don't fail here
                }
            }
        }
        try {
            signatureValue = this.beIDCard.sign(digestValue, beIDDigest, this.certificateFileType, false);
        } catch (Exception e) {
            if (this.autoRecovery) {
                LOG.debug("trying to recover...");
                this.beIDCard = this.beIDKeyStore.getBeIDCard(true);
                if (null != this.authenticationCertificate) {
                    X509Certificate newAuthenticationCertificate = this.beIDCard.getAuthenticationCertificate();
                    if (false == this.authenticationCertificate.equals(newAuthenticationCertificate)) {
                        throw new SignatureException("different eID card");
                    }
                }
            }
            signatureValue = this.beIDCard.sign(digestValue, beIDDigest, this.certificateFileType, false);
        }
        if (this.logoff) {
            this.beIDCard.logoff();
        }
    } catch (final Exception ex) {
        throw new SignatureException(ex);
    }
    return signatureValue;
}

From source file:uk.ac.bbsrc.tgac.miso.core.security.PasswordCodecService.java

/**
 * Encrypt a plaintext String using a hmac_sha1 salt
 *
 * @param key of type String/*from ww  w  . j av  a 2s  . c  o m*/
 * @param plaintext of type String
 * @return String the encrypted String of the given plaintext String
 * @throws SignatureException when the HMAC is unable to be generated
 */
public synchronized String encryptHMACSHA1(String key, String plaintext)
        throws java.security.SignatureException {
    String result;
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(plaintext.getBytes());

        // base64-encode the hmac
        //result = new BASE64Encoder().encode(rawHmac);
        result = new Base64().encodeToString(rawHmac);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);/* w  ww . jav a 2s  .  com*/

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.xdi.oxauth.model.jws.RSASigner.java

@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }// w  ww.ja v a 2  s. c  om
    if (rsaPublicKey == null) {
        throw new SignatureException("The RSA public key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }

    String algorithm = null;
    switch (getSignatureAlgorithm()) {
    case RS256:
        algorithm = "SHA-256";
        break;
    case RS384:
        algorithm = "SHA-384";
        break;
    case RS512:
        algorithm = "SHA-512";
        break;
    default:
        throw new SignatureException("Unsupported signature algorithm");
    }

    ASN1InputStream aIn = null;
    try {
        byte[] sigBytes = JwtUtil.base64urldecode(signature);
        byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);

        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
                rsaPublicKey.getPublicExponent());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] decSig = cipher.doFinal(sigBytes);
        aIn = new ASN1InputStream(decSig);

        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance(algorithm, "BC");
        hash.update(sigInBytes);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } catch (IOException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (NoSuchPaddingException e) {
        throw new SignatureException(e);
    } catch (BadPaddingException e) {
        throw new SignatureException(e);
    } catch (NoSuchProviderException e) {
        throw new SignatureException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SignatureException(e);
    } catch (Exception e) {
        throw new SignatureException(e);
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}