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.amazonaws.cbui.AmazonFPSCBUIPipeline.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *//*from  w  w  w  .  jav a2s  .c om*/
private static String sign(String data, String key, String signatureMethod) throws SignatureException {
    String signature = "";
    try {
        Mac mac = Mac.getInstance(signatureMethod);
        mac.init(new SecretKeySpec(key.getBytes(), signatureMethod));
        signature = new String(Base64.encodeBase64(mac.doFinal(data.getBytes(UTF_8_Encoding))));
    } catch (Exception e) {
        throw new SignatureException("Failed to generate signature: " + e.getMessage(), e);
    }
    return signature;
}

From source file:air.com.snagfilms.cast.chromecast.utils.Utils.java

public static String getfilmriseParameters(Context ctx) {

    StringBuilder strBlr = null;/*from   w  ww  . j a  va 2 s.co  m*/
    try {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        long longs = System.currentTimeMillis();
        String timestamp = dateFormat.format(longs);
        ;
        String stringToSign = timestamp; // Query uses this string

        // Compute the signature and base64 encode it.
        String algorithm = "HmacSHA1";
        SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(key);

        String signature = new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes())));
        System.out.println(signature);// required for Query
        signature = URLEncoder.encode(signature, "UTF-8");

        strBlr = new StringBuilder();
        strBlr.append(Constants.ACCESS_KEY);
        strBlr.append("=");
        strBlr.append(ACCESS_KEY);

        strBlr.append("&");
        strBlr.append(Constants.TIME_STAMP);
        strBlr.append("=");
        strBlr.append(timestamp);

        strBlr.append("&");
        strBlr.append(Constants.SIGNATURE);
        strBlr.append("=");
        strBlr.append(signature);

        strBlr.append("&");
        strBlr.append(Constants.SITE);
        strBlr.append("=");
        strBlr.append(Constants.filmrise);

        strBlr.append("&");
        strBlr.append(Constants.DEVICE);
        strBlr.append("=");
        strBlr.append("android");

        return strBlr.toString();

    } catch (Exception e) {

    }
    return null;
}

From source file:com.ublish.service.BasicLTIService.java

private String getSignature(OAuthMessage message, String secret) throws OAuthException {
    try {/*from w  w  w .j  ava2 s .  co m*/
        String baseString = getBaseString(message);

        byte[] keyBytes = (secret + "&").getBytes(UTF8);

        SecretKey secretKey = new SecretKeySpec(keyBytes, LaunchParameters.OAUTH_SIGNATURE_METHOD_HMACSHA1);

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);

        return Base64Codec.encode(mac.doFinal(baseString.getBytes(UTF8))).trim();
    } catch (Exception e) {
        throw new OAuthException("An exception occurred while creating the OAuth signature.", e);
    }
}

From source file:OAUTHnesia.java

private static String sha1(String s, String keyString)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);/*ww  w . ja va  2 s .co  m*/

    byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));

    return new String(Base64.encode(bytes, Base64.DEFAULT));
}

From source file:com.axelor.apps.account.service.payment.PayboxService.java

/**
 * Fonction calculant la signature HMAC des paramtres
 * @param data/*  w  w w .  j a  va2 s .  com*/
 *          La chaine contenant les paramtres
 * @param hmacKey
 *          La cl HMAC
 * @param algorithm
 *          L'algorithme utilis (SHA512, ...)
 * @return
 * @throws AxelorException
 */
public String getHmacSignature(String data, String hmacKey, String algorithm) throws AxelorException {
    try {

        byte[] bytesKey = DatatypeConverter.parseHexBinary(hmacKey);
        SecretKeySpec secretKey = new SecretKeySpec(bytesKey, "Hmac" + algorithm);
        Mac mac = Mac.getInstance("Hmac" + algorithm);
        mac.init(secretKey);

        byte[] macData = mac.doFinal(data.getBytes(this.CHARSET));

        //         final byte[] hex = new Hex().encode( macData );
        //         return new String( hex, this.CHARSET );
        //         LOG.debug("Message HMAC 2 : {}",new String( hex, this.CHARSET ));

        String s = StringTool.getHexString(macData);

        return s.toUpperCase();

    } catch (InvalidKeyException e) {
        throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e),
                IException.INCONSISTENCY);
    } catch (NoSuchAlgorithmException e) {
        throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e),
                IException.INCONSISTENCY);
    } catch (UnsupportedEncodingException e) {
        throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e),
                IException.INCONSISTENCY);
    }
}

From source file:ch.threema.apitool.CryptTool.java

/**
 * Hashes an email address for identity lookup.
 *
 * @param email the email address//from   w w w.j  a va2  s . c o m
 * @return the raw hash
 */
public static byte[] hashEmail(String email) {
    try {
        Mac emailMac = Mac.getInstance("HmacSHA256");
        emailMac.init(new SecretKeySpec(EMAIL_HMAC_KEY, "HmacSHA256"));
        String normalizedEmail = email.toLowerCase().trim();
        return emailMac.doFinal(normalizedEmail.getBytes("US-ASCII"));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.MainFiles.Functions.java

public String encryptPin(String username, String plainPassword, String strKey) {
    String plainString = username + plainPassword;
    byte[] byteArray = Base64.encodeBase64(plainString.getBytes());
    String encodedString = new String(byteArray);
    String HMAC_SHA512 = "HmacSHA512";
    String DEFAULT_ENCODING = "UTF-8";
    byte[] result = null;

    //Hash Algorithm
    try {/*w  w  w. j  av  a  2s .com*/
        SecretKeySpec keySpec = new SecretKeySpec(strKey.getBytes(DEFAULT_ENCODING), HMAC_SHA512);
        Mac mac = Mac.getInstance(HMAC_SHA512);
        mac.init(keySpec);
        result = mac.doFinal(encodedString.getBytes(DEFAULT_ENCODING));

    } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException ex) {
        this.log("INFO strResponseFooter() ::" + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "ERROR");
    }

    StringBuilder sb = new StringBuilder();
    for (byte b : result) {
        sb.append(String.format("%02X", b));
    }

    return sb.toString();
}

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

/**
 * Encrypt token data/*from  ww  w .  ja va2s .  co m*/
 *
 * @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.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Base64 decodes a given string//w w w  . ja  v  a  2 s. co  m
 *
 * @param variance - The allowed differences in OTP values
 * @param algorithm - The algorithm to encrypt the data with
 * @param instance - The security instance to utilize
 * @param secret - The OTP secret
 * @param code - The OTP code
 * @return <code>true</code> if successful, <code>false</code> otherwise
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final boolean validateOtpValue(final int variance, final String algorithm, final String instance,
        final String secret, final int code) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", variance);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", instance);
        DEBUGGER.debug("Value: {}", secret);
        DEBUGGER.debug("Value: {}", code);
    }

    long truncatedHash = 0;
    byte[] data = new byte[8];
    long timeIndex = System.currentTimeMillis() / 1000 / 30;

    final Base32 codec = new Base32();
    final byte[] decoded = codec.decode(secret);
    SecretKeySpec signKey = new SecretKeySpec(decoded, algorithm);

    if (DEBUG) {
        DEBUGGER.debug("long: {}", timeIndex);
    }

    try {
        for (int i = 8; i-- > 0; timeIndex >>>= 8) {
            data[i] = (byte) timeIndex;
        }

        Mac mac = Mac.getInstance(instance);
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;

        for (int i = 0; i < 4; i++) {
            truncatedHash <<= 8;
            truncatedHash |= (hash[offset + i] & 0xFF);
        }

        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;

        if (DEBUG) {
            DEBUGGER.debug("truncatedHash: {}", truncatedHash);
        }

        return (truncatedHash == code);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    }
}