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:com.epl.ticketws.services.QueryService.java

/**
 * Signs a string with the given key.//from www .  j a  v a  2 s.  c  om
 *
 * @param data
 * @param key
 * @return
 * @throws SignatureException
 */
private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException {
    String result;

    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), 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(UTF_8));
        //byte[] base64 = Base64.encodeBase64(rawHmac);
        byte[] base64 = Base64.getEncoder().encode(rawHmac);

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

    return AUTHORIZATION_HEADER_HMAC_PREFIX + result;
}

From source file:com.cloud.bridge.util.EC2RestAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1 or SHA256 ( key, byte array )))
 * //from   w  w w.  j a v a2s  .co  m
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @param useSHA1   - if false use SHA256
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey, boolean useSHA1)
        throws SignatureException {
    SecretKeySpec key = null;
    Mac hmacShaAlg = null;
    String result = null;

    try {
        if (useSHA1) {
            key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
            hmacShaAlg = Mac.getInstance("HmacSHA1");
        } else {
            key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
            hmacShaAlg = Mac.getInstance("HmacSHA256");
        }

        hmacShaAlg.init(key);
        byte[] rawHmac = hmacShaAlg.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));

    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:com.wandisco.s3hdfs.auth.AWSAuthenticationHandler.java

/**
 * Create a signature by the following method:
 * new String( Base64( SHA1 or SHA256 ( key, byte array )))
 *
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @param useSHA1   - if false use SHA256
 * @return String   - the recalculated string
 * @throws SignatureException// w w  w.  j av  a  2  s  . com
 */
private String calculateRFC2104HMAC(String signIt, String secretKey, boolean useSHA1)
        throws SignatureException {
    SecretKeySpec key = null;
    Mac hmacShaAlg = null;
    String result = null;

    try {
        if (useSHA1) {
            key = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), "HmacSHA1");
            hmacShaAlg = Mac.getInstance("HmacSHA1");
        } else {
            key = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), "HmacSHA256");
            hmacShaAlg = Mac.getInstance("HmacSHA256");
        }

        hmacShaAlg.init(key);
        byte[] rawHmac = hmacShaAlg.doFinal(signIt.getBytes(DEFAULT_CHARSET));
        result = new String(Base64.encodeBase64(rawHmac), DEFAULT_CHARSET);

    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

protected byte[] getDeviceListSignature(Connection con) throws SQLException, SignatureException {
    PreparedStatement s = con.prepareStatement(QUERY_SIGNATURE);
    ResultSet rs = s.executeQuery();
    if (rs.next()) {
        byte[] result = rs.getBytes(COL_SIGNATURE);
        if (rs.next()) {
            logger.error("More than one device list signature found");
            throw new SignatureException("More than one device list signature found");
        }/*from w  w  w  .  java2s .  co m*/
        rs.close();
        s.close();
        return result;
    } else {
        rs.close();
        s.close();
        // throw new
        // SignatureException("No signature found for device list");
        return null;
    }
}

From source file:com.amazonaws.cbui.AmazonFPSCBUIPipeline.java

/**
 * Calculate String to Sign for SignatureVersion 2
 * //w  w  w  . jav  a2s  . co  m
 * @param parameters
 * @param httpMethod - POST or GET
 * @param hostHeader - Service end point
 * @param requestURI - Path
 * @return
 * @throws SignatureException
 */
private 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(urlEncode(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(urlEncode(pair.getKey(), false));
        stringToSign.append(Equals);
        stringToSign.append(urlEncode(pair.getValue(), false));
        if (pairs.hasNext())
            stringToSign.append(And);
    }
    return stringToSign.toString();
}

From source file:es.onebox.rest.utils.service.QueryService.java

/**
 * Signs a string with the given key.//from   w  w w .  ja v a2  s .c om
 *
 * @param data
 * @param key
 * @return
 * @throws SignatureException
 */
private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException {
    String result;

    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), 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(UTF_8));
        byte[] base64 = Base64.encodeBase64(rawHmac);

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

    return AUTHORIZATION_HEADER_HMAC_PREFIX + result;
}

From source file:org.apache.camel.converter.crypto.PGPDataFormat.java

public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception {
    if (encryptedStream == null) {
        return null;
    }/*from w  ww  .ja v a2 s .  c  om*/

    PGPPrivateKey key = PGPDataFormatUtil.findPrivateKey(exchange.getContext(), findKeyFileName(exchange),
            encryptedStream, findKeyPassword(exchange));
    if (key == null) {
        throw new IllegalArgumentException("Private key is null, cannot proceed");
    }

    InputStream in;
    try {
        byte[] encryptedData = IOUtils.toByteArray(encryptedStream);
        InputStream byteStream = new ByteArrayInputStream(encryptedData);
        in = PGPUtil.getDecoderStream(byteStream);
    } finally {
        IOUtils.closeQuietly(encryptedStream);
    }

    PGPObjectFactory pgpFactory = new PGPObjectFactory(in);
    Object o = pgpFactory.nextObject();

    // the first object might be a PGP marker packet
    PGPEncryptedDataList enc;
    if (o instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) o;
    } else {
        enc = (PGPEncryptedDataList) pgpFactory.nextObject();
    }
    IOHelper.close(in);

    PGPPublicKeyEncryptedData pbe = (PGPPublicKeyEncryptedData) enc.get(0);
    InputStream encData = pbe
            .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(key));
    pgpFactory = new PGPObjectFactory(encData);
    PGPCompressedData comData = (PGPCompressedData) pgpFactory.nextObject();

    pgpFactory = new PGPObjectFactory(comData.getDataStream());
    Object object = pgpFactory.nextObject();

    PGPOnePassSignature signature;
    if (object instanceof PGPOnePassSignatureList) {
        signature = getSignature(exchange, (PGPOnePassSignatureList) object);
        object = pgpFactory.nextObject();
    } else {
        signature = null;
    }

    PGPLiteralData ld = (PGPLiteralData) object;
    InputStream litData = ld.getInputStream();

    byte[] answer;
    try {
        answer = Streams.readAll(litData);
    } finally {
        IOHelper.close(litData, encData, in);
    }

    if (signature != null) {
        signature.update(answer);
        PGPSignatureList sigList = (PGPSignatureList) pgpFactory.nextObject();
        if (!signature.verify(sigList.get(0))) {
            throw new SignatureException("Cannot verify PGP signature");
        }
    }

    return answer;
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void verifyDeviceList(ShareMetaData smd, PublicKey masterPubKey, DeviceList list)
        throws SignatureException {
    Collection<PublicKey> pKeys = list.getPublicKeys();
    byte[] signature = list.getSignature();
    if (signature == null) {
        logger.fatal("No signature for devicelist found");
        throw new SignatureException("No signature for devicelist found");
    }//ww  w . ja  v a2s .  c  o m
    boolean verified = false;
    try {
        // Either signed by the device list owner or by the
        // shareOwner
        Signable sKeys = smd.shareKeys.get(pKeys);
        Signable obKeys = smd.obfuscationKeys.get(pKeys);

        verified = SignatureHelper.verify(signature, masterPubKey, list, sKeys, obKeys);
        if (!verified) {
            verified = SignatureHelper.verify(signature, smd.ownerPubSigKey, list, sKeys, obKeys);
        }
    } catch (Exception e) {
        throw new SignatureException("Could not verify signature", e);
    }
    if (!verified) {
        logger.fatal("Could not verify devicelist");
        throw new SignatureException("Could not verify devicelist");
    }
}

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

/**
 * Fetches the public key certificate from the given url and caches it in
 * memory.//  ww w .ja  v  a2  s . c  o  m
 */
private String getPublicKeyCertificateAsString(String certificateUrl) throws SignatureException {
    // 1. Try to fetch from the in-memory cache
    String certificate = keyStore.get(certificateUrl);
    if (certificate != null)
        return certificate;

    // 2. If not found in cache, fetch it
    boolean followRedirects = HttpURLConnection.getFollowRedirects();
    HttpURLConnection.setFollowRedirects(false);
    try {
        certificate = URLReader.getUrlContents(certificateUrl);
    } catch (IOException e) {
        throw new SignatureException(e);
    } finally {
        HttpURLConnection.setFollowRedirects(followRedirects);
    }

    // 3. populate newly fetched certificate in cache.
    keyStore.put(certificateUrl, certificate);

    return certificate;
}

From source file:uk.ac.tgac.bbsrc.miso.external.ajax.ExternalSectionControllerHelperService.java

public static String calculateHMAC(String data, String key) throws java.security.SignatureException {
    String result;//from   w w  w .  j a v  a2 s  . c  om
    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(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;
}