Example usage for javax.crypto Mac init

List of usage examples for javax.crypto Mac init

Introduction

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

Prototype

public final void init(Key key) throws InvalidKeyException 

Source Link

Document

Initializes this Mac object with the given key.

Usage

From source file:com.cloud.utils.EncryptionUtil.java

public static String generateSignature(String data, String key) {
    try {/* w w w. j  a v a2  s  .  c  om*/
        final Mac mac = Mac.getInstance("HmacSHA1");
        final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
        mac.init(keySpec);
        mac.update(data.getBytes("UTF-8"));
        final byte[] encryptedBytes = mac.doFinal();
        return Base64.encodeBase64String(encryptedBytes);
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
        s_logger.error("exception occurred which encoding the data." + e.getMessage());
        throw new CloudRuntimeException("unable to generate signature", e);
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

private static String computeSignature(String baseString, String keyString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey secretKey = null;//from  w  ww . j ava  2  s .c  o m

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

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

    byte[] text = baseString.getBytes();

    return new String(BASE64Encoder.encode(mac.doFinal(text))).trim();
}

From source file:fr.ortolang.diffusion.security.authentication.TOTPHelper.java

private static byte[] hmacSha(byte[] keyBytes, byte[] text) {
    try {//w w w .jav a 2  s  .  c  o  m
        Mac hmac;
        hmac = Mac.getInstance("HmacSHA1");
        SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
        hmac.init(macKey);
        return hmac.doFinal(text);
    } catch (GeneralSecurityException gse) {
        throw new UndeclaredThrowableException(gse);
    }
}

From source file:com.google.resting.rest.util.oauth.SignatureUtil.java

/**
 * Sign request./*w w w . j  av  a2s . com*/
 * 
 * @param keyString Consumer key for request signing.
 * @param targetDomain Domain of the REST endpoint (Ex. login.yahoo.com)
 * @param verb Type of REST operation (GET/POST/PUT/DELETE)
 * @param isSecureInvocation HTTP/HTTPS
 * @param contextPathElement Path element in the base REST uri (Ex. /weather/india)
 * @param inputParams Collection of request params for REST request (Ex. city=calcutta )
 * @return
 * @throws NoSuchAlgorithmException The exception is thrown if the encryption algorithm is not supported.
 * @throws InvalidKeyException The exception is thrown if the consumer key is invalid
 * @throws IllegalStateException 
 * @throws UnsupportedEncodingException The exception is thrown if the URL encoding is incorrect.
 */
public static String getSignature(String keyString, String targetDomain, Verb verb, boolean isSecureInvocation,
        String contextPathElement, List<NameValuePair> inputParams, String messageEncoding)
        throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {

    String baseString = getBaseString(targetDomain, verb.toString(), isSecureInvocation, contextPathElement,
            inputParams, messageEncoding).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");

    System.out.println("Base string is " + baseString);
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(keyString.getBytes(messageEncoding), mac.getAlgorithm());
    mac.init(secret);
    byte[] digest = mac.doFinal(baseString.getBytes(messageEncoding));
    return new String(Base64.encodeBase64(digest)).replace(RequestConstants.CARRIAGE_RETURN,
            RequestConstants.EMPTY_STRING);
}

From source file:Models.UserModel.java

public static String HMAC_SHA256(String email, String password) {
    try {/*from w ww. j  av a  2  s . c  o m*/

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(password.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String auth = Base64.encodeBase64String(sha256_HMAC.doFinal(email.getBytes()));
        return auth;
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException e) {
        System.out.println("Error HS-256");
        return "";
    }
}

From source file:com.iorga.iraj.security.SecurityUtils.java

public static String computeDataSignature(final String secretAccessKey, final String data)
        throws NoSuchAlgorithmException, InvalidKeyException {
    final SecretKeySpec secretKeySpec = new SecretKeySpec(secretAccessKey.getBytes(UTF8_CHARSET), "HmacSHA1");
    final Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKeySpec);
    final String signature = Base64.encodeBase64String(mac.doFinal(data.getBytes(UTF8_CHARSET)));
    return StringUtils.chomp(signature);
}

From source file:mp3downloader.ZingSearch.java

private static String hash_hmac(String data, String key) {
    try {/*  w  w  w  .j a va2s .c o  m*/
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacMD5");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContext.java

/**
 * Calculates the checksum for the given string, using the given Mac instance and secret key.
 * @param mac The Mac instance./* w w w .  ja va 2  s . c  om*/
 * @param string The seed.
 * @param key The secret key used for calculating the checksum.
 * @return The checksum value.
 */
public static String calculateChecksum(final Mac mac, final String string, final SecretKey key) {
    try {
        mac.init(key);
        final byte[] bytes = mac.doFinal(string.getBytes("UTF-8"));
        return new String(Hex.encodeHex(bytes));
    } catch (InvalidKeyException | UnsupportedEncodingException e) {
        LoggerFactory.getLogger(InitializeStaticWilmaContext.class)
                .error("Could not sign the input data {} with the key", string);
    }
    return null;
}

From source file:ch.cyberduck.core.sftp.openssh.OpenSSHHostKeyVerifier.java

private static byte[] hmacSha1Hash(byte[] salt, String hostname) throws IOException {
    try {/*ww w.  j  a  va  2 s.com*/
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(salt, 0, salt.length, mac.getAlgorithm()));
        mac.update(hostname.getBytes());
        return mac.doFinal();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:chronic.app.ChronicCookie.java

public static String createAuthCode(byte[] secret, String string, long value) throws GeneralSecurityException {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1");
    mac.init(signKey);
    mac.update(string.getBytes());//ww  w.  jav a  2s . com
    return new Base32().encodeAsString(mac.doFinal(Bytes.toByteArray(value)));
}