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:org.apache.cloudstack.region.RegionsApiUtil.java

/**
 * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result
 *
 * @param request//  w  ww . j a v  a  2 s. c om
 * @param key
 * @return
 */
private static String signRequest(String request, String key) {
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8");
    } catch (Exception ex) {
        s_logger.error(ex.getMessage());
        return null;
    }
}

From source file:jp.primecloud.auto.api.ApiFilter.java

/**
 *
 * HMAC-SHA256???/*w  w  w. j  a va2s .co m*/
 *
 * @param plainText ?
 * @param keyText
 * @return
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 */
private static String encodeSHA256(String plainText, String keyText)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    SecretKey secretKey = new SecretKeySpec(keyText.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKey);

    byte[] plainBytes = plainText.getBytes("UTF-8");
    byte[] encodedBytes = mac.doFinal(plainBytes);
    byte[] hexBytes = new Hex().encode(encodedBytes);

    return new String(hexBytes, "UTF-8");
}

From source file:org.davidmendoza.fileUpload.web.VideoController.java

private String sign(String toSign)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    Mac hmac = Mac.getInstance("HmacSHA1");
    hmac.init(new SecretKeySpec(awsSecretKey.getBytes("UTF-8"), "HmacSHA1"));

    String signature = DatatypeConverter.printBase64Binary(hmac.doFinal(toSign.getBytes("UTF-8")))
            .replaceAll("\n", "");

    return signature;
}

From source file:com.microsoft.windowsazure.messaging.Connection.java

/**
 * Generates an AuthToken/* www .  ja va  2 s  .  c  o  m*/
 * @param url   The target URL
 * @return   An AuthToken
 * @throws java.security.InvalidKeyException
 */
private String generateAuthToken(String url) throws InvalidKeyException {

    String keyName = mConnectionData.get(SHARED_ACCESS_KEY_NAME);
    if (isNullOrWhiteSpace(keyName)) {
        throw new AssertionError("SharedAccessKeyName");
    }

    String key = mConnectionData.get(SHARED_ACCESS_KEY);
    if (isNullOrWhiteSpace(key)) {
        throw new AssertionError("SharedAccessKey");
    }

    try {
        url = URLEncoder.encode(url, UTF8_ENCODING).toLowerCase(Locale.ENGLISH);
    } catch (UnsupportedEncodingException e) {
        // this shouldn't happen because of the fixed encoding
    }

    // Set expiration in seconds
    Calendar expireDate = Calendar.getInstance(TimeZone.getTimeZone(UTC_TIME_ZONE));
    expireDate.add(Calendar.MINUTE, EXPIRE_MINUTES);

    long expires = expireDate.getTimeInMillis() / 1000;

    String toSign = url + '\n' + expires;

    // sign

    byte[] bytesToSign = toSign.getBytes();
    Mac mac = null;
    try {
        mac = Mac.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e) {
        // This shouldn't happen because of the fixed algorithm
    }

    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] signedHash = mac.doFinal(bytesToSign);
    String base64Signature = Base64.encodeToString(signedHash, Base64.DEFAULT);
    base64Signature = base64Signature.trim();
    try {
        base64Signature = URLEncoder.encode(base64Signature, UTF8_ENCODING);
    } catch (UnsupportedEncodingException e) {
        // this shouldn't happen because of the fixed encoding
    }

    // construct authorization string
    String token = "SharedAccessSignature sr=" + url + "&sig=" + base64Signature + "&se=" + expires + "&skn="
            + keyName;

    return token;
}

From source file:io.syndesis.rest.v1.state.ClientSideState.java

static byte[] mac(final String authenticationAlgorithm, final CharSequence base,
        final SecretKey authenticationKey) {
    try {// w w  w. jav a  2 s.  c o m
        final String baseString = base.toString();

        final Mac mac = Mac.getInstance(authenticationAlgorithm);
        mac.init(authenticationKey);

        // base contains only BASE64 characters and '|', so we use ASCII
        final byte[] raw = baseString.getBytes(StandardCharsets.US_ASCII);

        return mac.doFinal(raw);
    } catch (final GeneralSecurityException e) {
        throw new IllegalStateException("Unable to compute MAC of the given value", e);
    }
}

From source file:org.apache.nifi.processors.standard.util.crypto.scrypt.Scrypt.java

/**
 * Implementation of the <a href="http://www.tarsnap.com/scrypt/scrypt.pdf">scrypt KDF</a>.
 *
 * @param password password/*w  ww. ja  va  2  s.c  o m*/
 * @param salt     salt
 * @param n        CPU cost parameter
 * @param r        memory cost parameter
 * @param p        parallelization parameter
 * @param dkLen    intended length of the derived key in bits
 * @return the derived key
 * @throws GeneralSecurityException when HMAC_SHA256 is not available
 */
protected static byte[] deriveScryptKey(byte[] password, byte[] salt, int n, int r, int p, int dkLen)
        throws GeneralSecurityException {
    if (n < 2 || (n & (n - 1)) != 0) {
        throw new IllegalArgumentException("N must be a power of 2 greater than 1");
    }

    if (r < 1) {
        throw new IllegalArgumentException("Parameter r must be 1 or greater");
    }

    if (p < 1) {
        throw new IllegalArgumentException("Parameter p must be 1 or greater");
    }

    if (n > MAX_VALUE / 128 / r) {
        throw new IllegalArgumentException("Parameter N is too large");
    }

    // Must be enforced before r check
    if (p > MAX_VALUE / 128) {
        throw new IllegalArgumentException("Parameter p is too large");
    }

    if (r > MAX_VALUE / 128 / p) {
        throw new IllegalArgumentException("Parameter r is too large");
    }

    if (password == null || password.length == 0) {
        throw new IllegalArgumentException("Password cannot be empty");
    }

    int saltLength = salt == null ? 0 : salt.length;
    if (salt == null || saltLength == 0) {
        // Do not enforce this check here. According to the scrypt spec, the salt can be empty. However, in the user-facing ScryptCipherProvider, enforce an arbitrary check to avoid empty salts
        logger.warn("An empty salt was used for scrypt key derivation");
        //            throw new IllegalArgumentException("Salt cannot be empty");
        // as the Exception is not being thrown, prevent NPE if salt is null by setting it to empty array
        if (salt == null)
            salt = new byte[] {};
    }

    if (saltLength < 8 || saltLength > 32) {
        // Do not enforce this check here. According to the scrypt spec, the salt can be empty. However, in the user-facing ScryptCipherProvider, enforce an arbitrary check of [8..32] bytes
        logger.warn("A salt of length {} was used for scrypt key derivation", saltLength);
        //            throw new IllegalArgumentException("Salt must be between 8 and 32 bytes");
    }

    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(password, "HmacSHA256"));

    byte[] b = new byte[128 * r * p];
    byte[] xy = new byte[256 * r];
    byte[] v = new byte[128 * r * n];
    int i;

    pbkdf2(mac, salt, 1, b, p * 128 * r);

    for (i = 0; i < p; i++) {
        smix(b, i * 128 * r, r, n, v, xy);
    }

    byte[] dk = new byte[dkLen / 8];
    pbkdf2(mac, b, 1, dk, dkLen / 8);
    return dk;
}

From source file:TimestreamsTests.java

/**
 * Generate an HMAC Based on example://from   w  w w .j av  a 2 s . c  o  m
 * http://stackoverflow.com/questions/6312544
 * /hmac-sha1-how-to-do-it-properly-in-java
 * 
 * @param value
 *            is a String to hash
 * @param key
 *            is the private key to hash with#
 * @param type
 *            is the Mac format to use such as HmacSHA256
 * @return The hmac
 */
private String hmacString(String value, String key, String type) {
    try {
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, type);

        // Get a Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(type);
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.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) {
        fail = e.getLocalizedMessage();
        return null;
    }
}

From source file:br.com.vpsa.oauth2android.token.MacTokenTypeDefinition.java

private static String calculateMAC(String key, String normalizedString, String algorithm) {
    String macString = "";
    try {/* w  w  w .j  av  a2  s  .c  o  m*/
        System.out.println("algorithm=" + algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key.getBytes(), algorithm));
        macString = Base64.encodeToString(mac.doFinal(normalizedString.getBytes()), Base64.DEFAULT);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex);
    }
    return macString;
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

private Mac hmacSha256(SecretKey key) {
    try {//from w w  w .j  a  v  a  2 s  .  c  om
        final Mac mac = Mac.getInstance(HMAC_KEY_ALGORITHM);
        mac.init(key);
        return mac;
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256.",
                e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("Invalid key", e);
    }
}

From source file:com.altcanvas.asocial.Twitter.java

private byte[] generateSignature(String data) {
    SecretKeySpec spec = null;/*from w  w  w.j a  v a2s.c  o m*/
    if (this.tokenSecret == null) {
        spec = new SecretKeySpec((Http.encode(OAUTH_CONSUMER_SECRET) + "&").getBytes(), HMACSHA1);
    } else {
        spec = new SecretKeySpec(
                (Http.encode(OAUTH_CONSUMER_SECRET) + "&" + Http.encode(tokenSecret)).getBytes(), HMACSHA1);
    }

    try {
        Mac mac = Mac.getInstance(HMACSHA1);
        mac.init(spec);
        byte[] byteHMAC = mac.doFinal(data.getBytes());
        return Base64.encodeBase64(byteHMAC);
    } catch (NoSuchAlgorithmException nsae) {
    } catch (InvalidKeyException ike) {
    }
    return null;
}