Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

In this page you can find the example usage for javax.crypto Mac getInstance.

Prototype

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

From source file:com.googlesource.gerrit.plugins.github.notification.WebhookServlet.java

/**
 * Calculates the expected signature of the payload
 *
 * @param payload payload to calculate a signature for
 * @return signature of the payload/*from w ww  .ja  v a  2s  . co  m*/
 * @see <a href=
 *      "https://developer.github.com/webhooks/securing/#validating-payloads-from-github">
 *      Validating payloads from GitHub</a>
 */
private byte[] getExpectedSignature(byte[] payload) {
    SecretKeySpec key = new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac hmac;
    try {
        hmac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        hmac.init(key);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Hmac SHA1 must be supported", e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e);
    }
    return hmac.doFinal(payload);
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * Verifies a request signature.//from ww w .j a  v  a  2 s.  c  o  m
 *
 * @param data      a payload.
 * @param signature a signature.
 * @return true if valid, false otherwise.
 */
private boolean verifySignature(@Nonnull String data, @Nonnull String signature) {
    if (this.secret == null) {
        logger.warn("No secret key specified. Signature checks will be skipped!");
        return true;
    }

    try {
        Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM);
        mac.init(this.secret);

        byte[] expected = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Arrays.equals(expected, Hex.decodeHex(signature.toCharArray()));
    } catch (InvalidKeyException | NoSuchAlgorithmException ex) {
        logger.error("Could not verify signature: " + ex.getMessage(), ex);
    } catch (DecoderException ex) {
        logger.warn("Could not decode signature: " + ex.getMessage(), ex);
    }

    throw new IllegalStateException("Could not verify signature");
}

From source file:com.comcast.cmb.common.util.AuthUtil.java

protected static byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws AmazonClientException {
    try {//from   w w w  .  ja v a2  s .co  m
        Mac mac = Mac.getInstance(algorithm.toString());
        mac.init(new SecretKeySpec(key, algorithm.toString()));
        return mac.doFinal(data);
    } catch (Exception e) {
        throw new AmazonClientException("Unable to calculate a request signature: " + e.getMessage(), e);
    }
}

From source file:com.epl.ticketws.services.QueryService.java

/**
 * Signs a string with the given key./*from  w  w  w .  jav a2s .c  o  m*/
 *
 * @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.playhaven.android.req.PlayHavenRequest.java

protected String createHmac(SharedPreferences pref, String content, boolean stripEquals)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    String secret = getString(pref, Secret);
    SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
    Mac hmac = Mac.getInstance(HMAC);
    hmac.init(key);// w  w  w. j  a  va2  s  .c  o m
    hmac.update(content.getBytes(UTF8));
    byte[] bytes = hmac.doFinal();
    String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim();
    if (stripEquals)
        derived = derived.replaceAll("=", "");

    return derived;
}

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  ava2  s  .c o  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.francetelecom.admindm.com.UDPConnectionRequest.java

/**
 * <p>//from w  ww  .ja  v a 2 s.  co  m
 * Authenticate the UDPConnectionRequest.
 * </p>
 * <p>
 * The following actions are performed:
 * <ul>
 * <li>check if the RequestURI SIG attribute is equal to the computed
 * signature.</li>
 * </ul>
 * </p>
 * 
 * @return true if authentication phase succeed else false.
 */
private boolean authenticate() {
    Log.debug("enter authenticate");

    try {
        Parameter connectionRequestPasswordParameter = parameterData
                .createOrRetrieveParameter(parameterData.getRoot() + CONNECTION_REQUEST_PASSWORD);
        String password = (String) connectionRequestPasswordParameter.getValue();
        Log.debug("password = " + password);
        // create a secret key
        SecretKeySpec signinKey = new SecretKeySpec(password.getBytes(), HMAC_SHA1_ALGORITHM);
        // get a Mac instance
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signinKey);
        // compute value
        String text = requestURI.getAttribute(RequestURIParser.TS)
                + requestURI.getAttribute(RequestURIParser.ID) + requestURI.getAttribute(RequestURIParser.UN)
                + requestURI.getAttribute(RequestURIParser.CN);
        Log.debug("text = " + text);
        // computed signature (ensure lower case character)
        byte[] signature = mac.doFinal(text.getBytes());
        String computedSignature = new String(Hex.encodeHex(signature)).toLowerCase();
        Log.debug("computed signature = " + computedSignature);
        // get the signature from the message
        String receivedSignature = requestURI.getAttribute(RequestURIParser.SIG);
        // ensure lower case
        receivedSignature = receivedSignature.toLowerCase();
        if (receivedSignature == null) {
            Log.error("signature key null");
            return false;
        } else {
            if (!receivedSignature.equals(computedSignature)) {
                Log.error("invalid signature");
                return false;
            }
        }
    } catch (Fault e) {
        Log.error("unable to get the " + "IGD.ManagementServer.ConnectionRequestPassword");
        return false;
    } catch (NoSuchAlgorithmException e) {
        Log.error("Unable to get the HMAC-SHA1 algo");
        return false;
    } catch (InvalidKeyException e) {
        Log.error("Unable to sign the key");
        return false;
    }
    Log.info("UDP Connection Request authenticated");
    return true;
}

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  a  v a2 s. co  m*/
 */
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:lumbermill.internal.aws.AWSV4SignerImpl.java

private byte[] hmacSHA256(String data, byte[] key) {
    try {//  w  ww  . j ava 2  s.  c  om
        final Mac mac = Mac.getInstance(HMAC_SHA256);
        mac.init(new SecretKeySpec(key, HMAC_SHA256));
        return mac.doFinal(data.getBytes(Charsets.UTF_8));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.konakart.actions.ipn.EPaybgAction.java

/**
 * /*from w ww .  j a  va2s .  c  om*/
 * @param mapping
 *            The ActionMapping used to select this instance
 * @param form
 *            The optional ActionForm bean for this request (if any)
 * @param request
 *            The HTTP request we are processing
 * @param response
 *            The HTTP response we are creating
 * 
 */
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    String encoded = null, checksum = null, username = null, password = null, secretKey = null;

    // The response print writer used to send a response back to ePay
    PrintWriter pw = null;

    if (log.isDebugEnabled()) {
        log.debug("*********** ePay Callback");
    }

    // Create thes outside of try / catch since they are needed in the case of a general
    // exception
    IpnHistoryIf ipnHistory = new IpnHistory();
    ipnHistory.setOrderId(-1);
    ipnHistory.setModuleCode(code);

    String sessionId = null;

    KKAppEng kkAppEng = null;

    try {
        // Get the PrintWriter from the response
        try {
            pw = response.getWriter();
            if (pw == null) {
                throw new Exception();
            }
        } catch (IOException e2) {
            e2.printStackTrace();
            throw new Exception("Could not get a PrintWriter for the response");
        }

        // Get an instance of the KonaKart engine
        kkAppEng = this.getKKAppEng(request, response);

        // We get from configurations, the username and password used to log into the engine
        // in order to save the changes of the IPN
        username = kkAppEng.getConfig(MODULE_PAYMENT_EPAYBG_CALLBACK_USERNAME);
        password = kkAppEng.getConfig(MODULE_PAYMENT_EPAYBG_CALLBACK_PASSWORD);

        if (username == null || password == null) {
            throw new Exception("The callback username and password must be defined for the epaybg module by"
                    + " setting the configuration variables MODULE_PAYMENT_EPAYBG_CALLBACK_USERNAME"
                    + " and MODULE_PAYMENT_EPAYBG_CALLBACK_PASSWORD");
        }

        // We log into the engine to get a session.
        sessionId = kkAppEng.getEng().login(username, password);
        kkAppEng.setSessionId(sessionId);
        if (sessionId == null) {
            throw new Exception("The callback username and password must be defined for the epaybg module by"
                    + " setting the configuration variables MODULE_PAYMENT_EPAYBG_CALLBACK_USERNAME"
                    + " and MODULE_PAYMENT_EPAYBG_CALLBACK_PASSWORD");
        }

        // Get the secret key
        secretKey = kkAppEng.getConfig(MODULE_PAYMENT_EPAYBG_SECRET);
        if (secretKey == null) {
            throw new Exception("The Configuration MODULE_PAYMENT_EPAYBG_SECRET must be set to the secret key"
                    + " shared between the merchant and ePay)");
        }

        // See if we need to send an email, by looking at the configuration
        String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS);
        boolean sendEmail = false;
        if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) {
            sendEmail = true;
        }

        // Process the parameters sent in the callback
        if (log.isDebugEnabled()) {
            log.debug("Callback Data :");
        }

        StringBuffer sb = new StringBuffer();
        String invoice = null, status = null, payTime = null, stan = null, bcode = null;
        if (request != null) {
            Enumeration en = request.getParameterNames();
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);

                if (log.isDebugEnabled()) {
                    log.debug("ParamName = " + paramName + " ParamValue = " + paramValue);
                }

                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(paramName);
                sb.append(" = ");
                sb.append(paramValue);

                // Capture important variables so that we can determine whether the
                // transaction was successful or not
                if (paramName != null) {
                    if (paramName.equalsIgnoreCase(EPaybgAction.checksum)) {
                        checksum = paramValue;
                    } else if (paramName.equalsIgnoreCase(EPaybgAction.encoded)) {
                        encoded = paramValue;
                    }
                }
            }

            // Save the data to the IpnHistory class
            ipnHistory.setGatewayFullResponse(sb.toString());

            if (encoded == null || checksum == null) {
                ipnHistory.setKonakartResultDescription(RET2_DESC);
                ipnHistory.setKonakartResultId(RET2);
                kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                pw.print("ERR=" + RET2_DESC + "\n");
                return null;
            }

            // Get a checksum for the data
            Mac sha = Mac.getInstance("HmacSHA1");
            sha.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"));

            byte[] mac = new byte[20];
            mac = sha.doFinal(encoded.getBytes());
            String calculatedChecksum = bytesToHex(mac);

            if (log.isDebugEnabled()) {
                log.debug("Calculated Checksum = " + calculatedChecksum);
            }

            // Check the checksum
            if (calculatedChecksum == null || !calculatedChecksum.equalsIgnoreCase(checksum)) {
                ipnHistory.setKonakartResultDescription(RET3_DESC);
                ipnHistory.setKonakartResultId(RET3);
                kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                pw.print("ERR=" + RET3_DESC + "\n");
                return null;
            }

            // Decode the data
            String decoded = null;
            try {
                byte[] decodedByteArray = Base64.decode(encoded);
                decoded = new String(decodedByteArray);

                if (log.isDebugEnabled()) {
                    log.debug("Decoded Data = \n" + decoded);
                }
            } catch (Exception e) {
                ipnHistory.setKonakartResultDescription(RET4_DESC + decoded);
                ipnHistory.setKonakartResultId(RET4);
                kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                pw.print("ERR=" + RET4_DESC + decoded + "\n");
                return null;
            }

            // At this point we have decode the data sent by ePay and now we have to get the
            // parameters
            String[] parmArray = decoded.split(":");
            for (int i = 0; i < parmArray.length; i++) {
                if (parmArray[i] != null) {
                    String[] innerArray = parmArray[i].split("=");
                    if (innerArray.length == 2) {
                        if (innerArray[0] != null && innerArray[0].equals("INVOICE")) {
                            invoice = innerArray[1].trim();
                            sb.append("&");
                            sb.append("INVOICE=");
                            sb.append(invoice);
                        } else if (innerArray[0] != null && innerArray[0].equals("STATUS")) {
                            status = innerArray[1].trim();
                            sb.append("&");
                            sb.append("STATUS=");
                            sb.append(status);
                            ipnHistory.setGatewayResult(status);
                        } else if (innerArray[0] != null && innerArray[0].equals("PAY_TIME")) {
                            payTime = innerArray[1].trim();
                            sb.append("&");
                            sb.append("PAY_TIME=");
                            sb.append(payTime);
                        } else if (innerArray[0] != null && innerArray[0].equals("STAN")) {
                            stan = innerArray[1].trim();
                            sb.append("&");
                            sb.append("STAN=");
                            sb.append(stan);
                        } else if (innerArray[0] != null && innerArray[0].equals("BCODE")) {
                            bcode = innerArray[1].trim();
                            sb.append("&");
                            sb.append("BCODE=");
                            sb.append(bcode);
                        }
                    }
                }
            }

            // Update the full response
            ipnHistory.setGatewayFullResponse(sb.toString());

            // Since we've verified the data with the secret key, the order number should be
            // equal to invoice
            int orderId;
            try {
                if (invoice == null) {
                    throw new Exception();
                }
                orderId = new Integer(invoice).intValue();
                ipnHistory.setOrderId(orderId);
            } catch (Exception e) {
                ipnHistory.setKonakartResultDescription(RET5_DESC + invoice);
                ipnHistory.setKonakartResultId(RET5);
                kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                pw.print("ERR=" + RET5_DESC + invoice + "\n");
                return null;
            }

            // If successful, we update the inventory as well as changing the state of the
            // order.
            String comment = null;
            if (status != null && status.equalsIgnoreCase("PAID")) {
                comment = ORDER_HISTORY_COMMENT_OK + status;
                kkAppEng.getEng().changeOrderStatus(sessionId, orderId,
                        com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, sendEmail, comment);
                // If the order payment was approved we update the inventory
                kkAppEng.getEng().updateInventory(sessionId, orderId);
                if (sendEmail) {
                    sendOrderConfirmationMail(kkAppEng, orderId, /* success */true);
                }

            } else {
                comment = ORDER_HISTORY_COMMENT_KO + status;
                kkAppEng.getEng().changeOrderStatus(sessionId, orderId,
                        com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, sendEmail, comment);
                if (sendEmail) {
                    sendOrderConfirmationMail(kkAppEng, orderId, /* success */false);
                }

            }

            ipnHistory.setKonakartResultDescription(RET0_DESC);
            ipnHistory.setKonakartResultId(RET0);
            kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);

        }

        pw.print("INVOICE=" + invoice + ":STATUS=OK\n");
        return null;

    } catch (Exception e) {
        try {
            if (sessionId != null) {
                ipnHistory.setKonakartResultDescription(RET6_DESC);
                ipnHistory.setKonakartResultId(RET6);
                if (kkAppEng != null) {
                    kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                }
            }
        } catch (KKException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
        if (pw != null) {
            pw.print("ERR=" + RET6_DESC + "\n");
        }
        return null;
    }

}