Example usage for javax.crypto Mac doFinal

List of usage examples for javax.crypto Mac doFinal

Introduction

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

Prototype

public final byte[] doFinal(byte[] input) throws IllegalStateException 

Source Link

Document

Processes the given array of bytes and finishes the MAC operation.

Usage

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

/**
 * /*from w  w  w.  ja va 2s .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;
    }

}

From source file:com.example.android.hawifi.MainActivity.java

public boolean throwCmd(String command) {
    final Charset asciiCs = Charset.forName("US-ASCII");
    long nonce = myTime();
    String HMAC_PASS = "password";
    String HMAC_KEY = "key";
    //String beforeHmac = "The quick brown fox jumps over the lazy dog";
    String beforeHmac = "/" + HMAC_PASS + "/" + command + "/" + nonce + "/";
    String result = "";
    try {/*w  w w . j ava  2s . c  o  m*/
        final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode(HMAC_KEY).array(),
                "HmacSHA256");
        sha256_HMAC.init(secret_key);
        final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode(beforeHmac).array());
        for (final byte element : mac_data) {
            result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
        }
    } catch (Exception e) {
        if (D)
            Log.e(TAG, "Crypto Exception");
    }

    DownloadTask dt;
    String url = null;
    if (((RadioButton) findViewById(R.id.radioButton0)).isChecked())
        url = myUrls[0].url;
    else if (((RadioButton) findViewById(R.id.radioButton1)).isChecked())
        url = myUrls[1].url;
    else if (((RadioButton) findViewById(R.id.radioButton2)).isChecked())
        url = myUrls[2].url;
    else if (((RadioButton) findViewById(R.id.radioButton3)).isChecked())
        url = myUrls[3].url;
    else if (((RadioButton) findViewById(R.id.radioButton4)).isChecked())
        url = myUrls[4].url;
    if (url != null) {
        //new DownloadTask().execute(url + command + "/" + nonce + "/" + result);
        dt = new DownloadTask();
        dt.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url + command + "/" + nonce + "/" + result);
    }
    Log.e(TAG, url + command);
    return true;
}

From source file:com.francetelecom.admindm.com.UDPConnectionRequest.java

/**
 * <p>//w  ww.  ja v  a2 s. c  o  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:me.vertretungsplan.parser.WebUntisParser.java

private int authCodeInternal(long time) throws NoSuchAlgorithmException, InvalidKeyException {
    long t = time / 30000;
    byte[] key = new Base32().decode(sharedSecret.toUpperCase().getBytes());
    byte[] data = new byte[8];
    long value = t;
    int i = 8;//from  w w  w  .  j  ava  2  s. c  o m
    while (true) {
        int i2 = i - 1;
        if (i <= 0) {
            break;
        }
        data[i2] = (byte) ((int) value);
        value >>>= 8;
        i = i2;
    }
    SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);
    int offset = hash[19] & 15;
    long truncatedHash = 0;
    for (int i2 = 0; i2 < 4; i2 += 1) {
        truncatedHash = (truncatedHash << 8) | ((long) (hash[offset + i2] & 255));
    }
    return (int) ((truncatedHash & 2147483647L) % 1000000);
}

From source file:com.example.android.vault.VaultProvider.java

/**
 * Load our symmetric secret key and use it to derive two different data and
 * MAC keys. The symmetric secret key is stored securely on disk by wrapping
 * it with a public/private key pair, possibly backed by hardware.
 *///from w w  w.j ava2 s .  c  o m
private void loadOrGenerateKeys(Context context, File keyFile) throws GeneralSecurityException, IOException {
    final SecretKeyWrapper wrapper = new SecretKeyWrapper(context, TAG);

    // Generate secret key if none exists
    if (!keyFile.exists()) {
        final byte[] raw = new byte[DATA_KEY_LENGTH];
        new SecureRandom().nextBytes(raw);

        final SecretKey key = new SecretKeySpec(raw, "AES");
        final byte[] wrapped = wrapper.wrap(key);

        writeFully(keyFile, wrapped);
    }

    // Even if we just generated the key, always read it back to ensure we
    // can read it successfully.
    final byte[] wrapped = readFully(keyFile);
    final SecretKey key = wrapper.unwrap(wrapped);

    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(key);

    // Derive two different keys for encryption and authentication.
    final byte[] rawDataKey = new byte[DATA_KEY_LENGTH];
    final byte[] rawMacKey = new byte[MAC_KEY_LENGTH];

    System.arraycopy(mac.doFinal(BLOB_DATA), 0, rawDataKey, 0, rawDataKey.length);
    System.arraycopy(mac.doFinal(BLOB_MAC), 0, rawMacKey, 0, rawMacKey.length);

    mDataKey = new SecretKeySpec(rawDataKey, "AES");
    mMacKey = new SecretKeySpec(rawMacKey, "HmacSHA256");
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*  w  w  w .ja va2 s. c om*/
 */
@Override
public final byte[] macSha256(byte[] dataToMac, byte[] key) throws McbpCryptoException {
    final String algorithm = "HmacSHA256";
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    try {
        Mac sha256Hmac = Mac.getInstance(algorithm);
        sha256Hmac.init(secretKey);
        return sha256Hmac.doFinal(dataToMac);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStore.java

@Override
public String getReference(@Nonnull String blobId) {
    checkNotNull(blobId, "BlobId must be specified");
    try {/*  w w w  .  jav  a2 s . c om*/
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(getReferenceKey(), ALGORITHM));
        byte[] hash = mac.doFinal(blobId.getBytes("UTF-8"));
        return blobId + ':' + BaseEncoding.base32Hex().encode(hash);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.twilio.sdk.TwilioUtils.java

public boolean validateRequest(String expectedSignature, String url, Map<String, String> params) {

    SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1");

    try {//from  www  . j  a  v a  2 s . com
        //initialize the hash algortihm
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        //sort the params alphabetically, and append the key and value of each to the url
        StringBuffer data = new StringBuffer(url);
        if (params != null) {
            List<String> sortedKeys = new ArrayList<String>(params.keySet());
            Collections.sort(sortedKeys);

            for (String s : sortedKeys) {
                data.append(s);
                String v = "";
                if (params.get(s) != null) {
                    v = params.get(s);
                }
                data.append(v);
            }
        }

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

        //base64-encode the hmac
        String signature = new String(Base64.encodeBase64(rawHmac));

        return signature.equals(expectedSignature);
    } catch (NoSuchAlgorithmException e) {

        return false;
    } catch (InvalidKeyException e) {

        return false;
    } catch (UnsupportedEncodingException e) {
        return false;
    }
}

From source file:org.gss_project.gss.server.rest.RequestHandler.java

/**
 * Calculates the signature for the specified data String and then
 * compares it against the provided signature. If the signatures match,
 * the method returns true. Otherwise it returns false.
 *
 * @param signature the signature to compare against
 * @param user the current user/*from   w w  w.  j  a  v a 2 s.c o m*/
 * @param data the data to sign
 * @return true if the calculated signature matches the supplied one
 */
protected boolean isSignatureValid(String signature, User user, String data) {
    if (logger.isDebugEnabled())
        logger.debug("server pre-signing data: " + data);
    String serverSignature = null;
    // If the authentication token is not valid, the user must get another one.
    if (user.getAuthToken() == null)
        return false;
    // Get an HMAC-SHA1 key from the authentication token.
    SecretKeySpec signingKey = new SecretKeySpec(user.getAuthToken(), HMAC_SHA1);
    try {
        // Get an HMAC-SHA1 Mac instance and initialize with the signing key.
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        // Compute the HMAC on input data bytes.
        byte[] rawHmac = mac.doFinal(data.getBytes());
        serverSignature = new String(Base64.encodeBase64(rawHmac), "US-ASCII");
    } catch (Exception e) {
        logger.error("Error while creating signature", e);
        return false;
    }

    if (logger.isDebugEnabled())
        logger.debug("Signature: client=" + signature + ", server=" + serverSignature);
    if (!serverSignature.equals(signature))
        return false;

    return true;
}