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:uk.ac.bbsrc.tgac.miso.integration.util.SignatureHelper.java

private static String calculateHMAC(String data, String key) throws java.security.SignatureException {
    String result;/*ww  w. j  av  a 2  s . co  m*/
    try {
        // 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 = Base64.encodeBase64URLSafeString(rawHmac);
    } catch (Exception e) {
        log.error("failed to generate HMAC", e);
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:com.runtimecollective.influence.metrics.Alexa.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * //w  w w  . j  av a  2s .  co  m
 * @param data
 *     The data to be signed.
 * @param key
 *     The signing key.
 * @return
 *     The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws
 *     java.security.SignatureException when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
    String result;
    try {
        // 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 sun.misc.BASE64Encoder().encode(rawHmac);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:tkwatch.Utilities.java

/**
 * Generates the signature necessary to make a TradeKing API call. Adapted
 * from the <i>TradeKing API Reference Guide</i>, 03.25.2011, p. 51.
 * //  w  w w . j a  v a2s.  c o m
 * @param data
 *            Concatenation of the API request body and a timestamp.
 * @param key
 *            The user's secret key.
 * @return Returns the necessary signature.
 * @throws java.security.SignatureException
 *             Thrown if the md5 hash-based message authentication code
 *             can't be generated.
 */
public static final String generateSignature(final String data, final String key)
        throws java.security.SignatureException {
    String result;
    try {
        byte[] encodedData = Base64.encodeBase64(data.getBytes());
        // Get an hmac_md5 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacMD5");
        // Get an hmac_md5 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(signingKey);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(encodedData);
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        // Covert array of Hex bytes to a String
        result = new String(hexBytes, "ISO-8859-1");
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java

/**
 * Verifies the signature using PKI.//from ww w  .java  2  s.c  om
 */
private boolean validateSignatureV2(Map<String, String> parameters, String urlEndPoint, String httpMethod)
        throws SignatureException {

    // 1. input validation.
    String signature = parameters.get(SIGNATURE_KEYNAME);
    if (signature == null) {
        throw new SignatureException("'signature' is missing from the parameters.");
    }

    String signatureMethod = parameters.get(SIGNATURE_METHOD_KEYNAME);
    if (signatureMethod == null) {
        throw new SignatureException("'signatureMethod' is missing from the parameters.");
    }

    String signatureAlgorithm = getSignatureAlgorithm(signatureMethod);
    if (signatureAlgorithm == null) {
        throw new SignatureException("'signatureMethod' present in parameters is invalid. "
                + "Valid signatureMethods are : 'RSA-SHA1'");
    }

    String certificateUrl = parameters.get(CERTIFICATE_URL_KEYNAME);
    if (certificateUrl == null) {
        throw new SignatureException("'certificateUrl' is missing from the parameters.");
    }

    String certificate = getPublicKeyCertificateAsString(certificateUrl);
    if (certificate == null) {
        throw new SignatureException("public key certificate could not fetched from url: " + certificateUrl);
    }

    // 2. calculating the string to sign
    String stringToSign = EMPTY_STRING;
    try {
        URL url = new URL(urlEndPoint);
        String hostHeader = getHostHeader(url);
        String requestURI = getRequestURI(url);
        stringToSign = calculateStringToSignV2(parameters, httpMethod, hostHeader, requestURI);
    } catch (MalformedURLException e) {
        throw new SignatureException(e);
    }

    // 3. verify signature
    try {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(certificate.getBytes()));
        Signature signatureInstance = Signature.getInstance(signatureAlgorithm);
        signatureInstance.initVerify(x509Certificate.getPublicKey());
        signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding));
        return signatureInstance.verify(Base64.decodeBase64(signature.getBytes()));
    } catch (CertificateException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }
}

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

@Override
protected boolean engineVerify(final byte[] sigBytes) throws SignatureException {
    LOG.debug("engineVerify");
    if (null == this.verifySignature) {
        throw new SignatureException("initVerify required");
    }//from  www  .j a  v a 2s .c  om
    final boolean result = this.verifySignature.verify(sigBytes);
    return result;
}

From source file:org.wso2.carbon.identity.core.util.IdentityUtil.java

public static String getHMAC(String secretKey, String baseString) throws SignatureException {
    try {/*from www . j  a  va2 s  .c  om*/
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes());
        return Base64.encode(rawHmac);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}

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

private byte[] calculateHmac(String data, String key) throws SignatureException {
    try {/*from www . j av  a  2s  .  c  o  m*/
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        return mac.doFinal(data.getBytes());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}

From source file:at.gv.egiz.bku.slcommands.impl.BulkCommandImpl.java

private List<byte[]> signBulkRequest(List<BulkSignatureInfo> bulkSignatureInfo, SLCommandContext commandContext,
        List<BulkSignature> signatures) throws SLCommandException, SLRequestException {

    try {//from w w w  .  ja  v  a  2 s.co m

        List<byte[]> signatureValues;

        BulkSignRequest signRequest = getSTALSignRequest(bulkSignatureInfo);

        // send BulkStalRequest
        List<STALResponse> responses = commandContext.getSTAL()
                .handleRequest(Collections.singletonList((STALRequest) signRequest));

        if (responses == null || responses.size() != 1) {
            throw new SignatureException("Failed to access STAL.");
        }

        STALResponse response = responses.get(0);

        // setSignatureValues from STALResponse  
        if (response instanceof BulkSignResponse) {
            BulkSignResponse bulkSignatureResponse = ((BulkSignResponse) response);

            signatureValues = new LinkedList<byte[]>();
            for (int i = 0; i < bulkSignatureResponse.getSignResponse().size(); i++) {
                byte[] sig = ((BulkSignResponse) response).getSignResponse().get(i).getSignatureValue();
                log.debug("Got signature response: " + Util.toBase64String(sig));
                signatures.get(i).getSignerInfo().setSignatureValue(
                        wrapSignatureValue(sig, bulkSignatureInfo.get(i).getSignatureAlgorithm()));
                signatureValues.add(signatures.get(i).getEncoded());
            }

            return signatureValues;

        } else if (response instanceof ErrorResponse) {

            ErrorResponse err = (ErrorResponse) response;
            log.debug("Error signing bulk request. Error response code: " + err.getErrorCode() + " ("
                    + err.getErrorMessage() + ").");
            throw new SLCommandException(err.getErrorCode());
        }

    } catch (SignatureException e) {
        log.error("Error creating CMSSignature", e);
        throw new SLCommandException(4000);
    } catch (CMSException e) {
        log.error("Error creating CMSSignature", e);
    }
    return null;
}

From source file:net.oauth.jsontoken.JsonToken.java

private String getSignature() throws SignatureException {
    if (signature != null && !signature.isEmpty()) {
        return signature;
    }//from ww w . j  a  va  2  s .  c o m

    if (signer == null) {
        throw new SignatureException("can't sign JsonToken with signer.");
    }
    String signature;
    // now, generate the signature
    AsciiStringSigner asciiSigner = new AsciiStringSigner(signer);
    signature = Base64.encodeBase64URLSafeString(asciiSigner.sign(baseString));

    return signature;
}