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:es.onebox.rest.utils.service.QueryService.java

/**
 * Signs a string with the given key.//  w  w  w. ja v a  2 s  .  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);

        // 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:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java

/**
 * Authenticate to the SMTP server by sending the AUTH command with the
 * selected mechanism, using the given username and the given password.
 * <p/>//  w  ww. jav a 2 s .  c  o  m
 *
 * @return True if successfully completed, false if not.
 * @throws SMTPConnectionClosedException              If the SMTP server prematurely closes the connection as a
 *                                                    result of the client being idle or some other reason
 *                                                    causing the server to send SMTP reply code 421. This
 *                                                    exception may be caught either as an IOException or
 *                                                    independently as itself.
 * @throws java.io.IOException                        If an I/O error occurs while either sending a command to
 *                                                    the server or receiving a reply from the server.
 * @throws java.security.NoSuchAlgorithmException     If the CRAM hash algorithm cannot be instantiated by the
 *                                                    Java runtime system.
 * @throws java.security.InvalidKeyException          If the CRAM hash algorithm failed to use the given
 *                                                    password.
 * @throws java.security.spec.InvalidKeySpecException If the CRAM hash algorithm failed to use the given
 *                                                    password.
 *                                                    *
 */
public boolean auth(AUTH_METHOD method, String username, String password)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
        return false;
    }

    if (method.equals(AUTH_METHOD.PLAIN)) {
        // the server sends an empty response ("334 "), so we don't have to
        // read it.
        return SMTPReply.isPositiveCompletion(sendCommand(
                new String(Base64.encodeBase64(("\000" + username + "\000" + password).getBytes()))));
    } else if (method.equals(AUTH_METHOD.CRAM_MD5)) {
        // get the CRAM challenge
        byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim());
        // get the Mac instance
        Mac hmac_md5 = Mac.getInstance("HmacMD5");
        hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5"));
        // compute the result:
        byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes();
        // join the byte arrays to form the reply
        byte[] usernameBytes = username.getBytes();
        byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
        System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
        toEncode[usernameBytes.length] = ' ';
        System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
        // send the reply and read the server code:
        return SMTPReply.isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(toEncode))));
    } else if (method.equals(AUTH_METHOD.LOGIN)) {
        // the server sends fixed responses (base64("Username") and
        // base64("Password")), so we don't have to read them.
        if (!SMTPReply
                .isPositiveIntermediate(sendCommand(new String(Base64.encodeBase64(username.getBytes()))))) {
            return false;
        }
        return SMTPReply
                .isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(password.getBytes()))));
    } else {
        return false; // safety check
    }
}

From source file:org.nimbustools.messaging.query.security.QueryAuthenticationFilter.java

private String createSignature(String s, String secretKey, String method) {

    final SecretKeySpec spec = new SecretKeySpec(secretKey.getBytes(), method);

    // these Macs may be expensive to create? perhaps need a caching scheme.
    // careful though, thread safety of Mac#doFinal() is unclear..

    final byte[] bytes;
    try {//from  ww  w.ja  v a 2 s  . co m
        final Mac mac = Mac.getInstance(method);
        mac.init(spec);
        bytes = mac.doFinal(s.getBytes("UTF-8"));

    } catch (NoSuchAlgorithmException e) {
        throw new QueryException(QueryError.SignatureDoesNotMatch,
                "Request used an unsupported signature method: " + method, e);
    } catch (InvalidKeyException e) {
        // I don't think this should happen..
        throw new QueryException(QueryError.SignatureDoesNotMatch, "Secret key is invalid", e);
    } catch (UnsupportedEncodingException e) {
        throw new QueryException(QueryError.SignatureDoesNotMatch, "Signature generation failed", e);
    }

    return new String(Base64.encodeBase64(bytes));
}

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

private boolean validateSignatureV1(Map<String, String> parameters) throws SignatureException {

    if (this.awsSecretKey == null) {
        throw new SignatureException("Signature can not be verified without aws secret key.");
    }/*from w  w  w .  j  a  v a 2  s . com*/

    String stringToSign = calculateStringToSignV1(parameters);
    String signature = parameters.get(SIGNATURE_KEYNAME);

    String result;
    try {
        SecretKeySpec signingKey = new SecretKeySpec(this.awsSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(stringToSign.getBytes("UTF-8"));
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    return result.equals(signature);
}

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

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * //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
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException {
    String result = null;
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (InvalidKeyException e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request because key " + secretKey
                + " is invalid" + e.getMessage());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java

/**
 * Encrypt token data/*from w  w  w.ja  va2s.  c om*/
 *
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
private String encryptData(String data) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), encryptionType);

    Mac mac = Mac.getInstance(encryptionType);
    mac.init(keySpec);
    byte[] result = mac.doFinal(data.getBytes());
    return StringUtils.trim(new Base64(true).encodeToString(result));
}

From source file:com.zxlim.totp.TOTP.java

private final byte[] hmac(final byte[] data) {
    final Mac mac;

    try {/*from ww  w .  jav a  2  s  . c  om*/
        mac = Mac.getInstance(HMAC_ALGORITHM, HMAC_PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        return null;
    }

    try {
        mac.init(new SecretKeySpec(secret, HMAC_ALGORITHM));
    } catch (InvalidKeyException e) {
        return null;
    }

    return mac.doFinal(data);
}

From source file:com.amazon.dtasdk.v2.signature.Signer.java

protected final byte[] sign(byte[] dataBytes, byte[] keyBytes) throws SigningException {
    try {/*from  w w w .  ja  v a2s  .  co m*/
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(keyBytes, ALGORITHM));
        return mac.doFinal(dataBytes);
    } catch (NoSuchAlgorithmException nsae) {
        throw new SigningException(nsae);
    } catch (InvalidKeyException ike) {
        throw new SigningException(ike);
    }
}

From source file:com.restswitch.controlpanel.MainActivity.java

private void sendDevice(String devid, String host, String msg, String pwdHash) {
    try {// w w  w  . j  a v  a  2  s  .co  m
        final long utcStart = System.currentTimeMillis();
        String b32UntilUtc = B32Coder.encodeDatetimeNow(8000); // valid for 8 sec
        String method = "PUT";
        String uri = ("/pub/" + devid);
        String val = (method + uri + msg + b32UntilUtc);

        String b64Hash = null;
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(new javax.crypto.spec.SecretKeySpec(pwdHash.getBytes("utf-8"), "HmacSHA256"));
            byte[] hash = hmacSha256.doFinal(val.getBytes("UTF-8"));
            b64Hash = Base64.encodeToString(hash, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
        } catch (Exception ex) {
            alertError("Invalid password, verify app settings.");
            return;
        }

        Properties headers = new Properties();
        headers.setProperty("x-body", msg);
        headers.setProperty("x-auth1", b32UntilUtc);
        headers.setProperty("x-auth2", b64Hash);

        AjaxTask ajaxTask = new AjaxTask();
        ajaxTask.putAjaxEventHandler(this);
        //            // use to set a custom ca
        //            boolean rc = ajaxTask.putRootCaCert(rootCa, true);
        //            if(!rc) {
        //                alertError("Failed to initialize network task.");
        //                return;
        //            }
        AjaxTask.Data data = new AjaxTask.Data();
        data.param1 = devid;
        data.param2 = utcStart;
        ajaxTask.invoke("http", host, uri, method, headers, msg, data);
    } catch (Exception ex) {
        alertError(ex.getMessage());
    }
}

From source file:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

protected byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws AmazonClientException {
    try {/*  w w  w  .  j  av 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);
    }
}