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.amediamanager.util.S3FormSigner.java

/**
 * The SignRequest method takes a set of AWS credentials and the S3 upload policy string and returns the encoded policy and the signature.
 *
 * @param creds        the AWS credentials to be used for signing the request
 * @param policy    the policy file to applied to the upload
 * @return            an array of strings containing the base 64 encoded policy (index 0) and the signature (index 1).
 *///from   w  ww . j  a va  2s.  co  m
String[] signRequest(AWSCredentialsProvider credsProvider, String policy) {

    String[] policyAndSignature = new String[2];

    try {
        // Create a Base64 encoded version of the policy string for placement in the form and
        // for use in signature generation.  Returns are stripped out from the policy string.
        String encodedPolicy = new String(
                Base64.encodeBase64(policy.replaceAll("\n", "").replaceAll("\r", "").getBytes("UTF-8")));

        // AWS signatures are generated using SHA1 HMAC signing.
        Mac hmac = Mac.getInstance("HmacSHA1");

        // Generate the signature using the Secret Key from the AWS credentials
        hmac.init(new SecretKeySpec(credsProvider.getCredentials().getAWSSecretKey().getBytes("UTF-8"),
                "HmacSHA1"));

        String signature = new String(Base64.encodeBase64(hmac.doFinal(encodedPolicy.getBytes("UTF-8"))));

        // Pack the encoded policy and the signature into a string array
        policyAndSignature[0] = encodedPolicy;
        policyAndSignature[1] = signature;

    } catch (UnsupportedEncodingException e) {
        LOG.error("Unsupport encoding", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("No such algorithm", e);
    } catch (InvalidKeyException e) {
        LOG.error("Invalid key", e);
    }

    return policyAndSignature;
}

From source file:com.rogoman.easyauth.HMAC.java

/**
 * Calculates the HMAC digest value based on the provided parameters.
 *
 * @param msg       Message/*from w  w w  . j  a v  a 2 s.c o m*/
 * @param secretKey Key to be used in the hashing process
 * @param algorithm HMAC algorithm to be used
 * @return HMAC digest
 * @throws java.security.NoSuchAlgorithmException thrown when the passed digest algorithm name cannot be recognized
 * @throws java.security.InvalidKeyException      thrown when the passed secret key value is invalid according to the digest algorithm
 */
static byte[] hmacDigest(final byte[] msg, final byte[] secretKey, final String algorithm)
        throws NoSuchAlgorithmException, InvalidKeyException {
    if (msg == null) {
        throw new IllegalArgumentException("msg is empty");
    }
    if (secretKey == null) {
        throw new IllegalArgumentException("secretKey is empty");
    }
    if (StringUtils.isEmpty(algorithm)) {
        throw new IllegalArgumentException("algo is empty");
    }

    SecretKeySpec key = new SecretKeySpec(secretKey, algorithm);
    Mac mac = Mac.getInstance(algorithm);
    mac.init(key);
    return mac.doFinal(msg);
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.service.UsuarioService.java

@POST
@Path("/agregarAmigos")
public List<UsuarioDTO> agregarAmigos(UsuarioAmigosDTO usuarioAmigos) throws Exception {

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    String key = "123";
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);/*from  ww w. j  av  a 2s . co  m*/

    String x = usuarioAmigos.toString();
    System.out.println("TO String: " + x);

    String hash = Hex.encodeHexString(sha256_HMAC.doFinal(x.getBytes()));
    System.out.println("CODIGO HASH: " + hash);
    System.out.println("CODIGO HASH JSON " + usuarioAmigos.getHash());

    boolean alterado = !(hash.equalsIgnoreCase(usuarioAmigos.getHash()));
    System.out.println("Alterado: " + alterado);

    if (alterado) {
        System.out.println("Alterado el sistema");
    }
    return this.usuarioLogicService.agregarAmigos(usuarioAmigos);
}

From source file:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java

@Override
protected void initFilterBean() throws ServletException {
    if (StringUtils.isBlank(sharedSecret)) {
        secretKey = null;/* w  ww  . j ava 2s .c  om*/
        return;
    }

    try {
        secretKey = new SecretKeySpec(sharedSecret.getBytes(), algorithm);

        // Initialize a mac instance to fail fast on NoSuchAlgorithmException or InvalidKeyException.
        // This way any configuration errors will prevent the application from starting instead of causing
        // problems later.
        final Mac mac = Mac.getInstance(algorithm);

        mac.init(secretKey);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException(e);
    } catch (InvalidKeyException e) {
        throw new ServletException(e);
    }
}

From source file:org.apereo.openlrs.utils.OAuthUtils.java

public static String sign(String secret, Map<String, String> oauthParameters, String algorithm, String method,
        String url) {/*from w w w .  ja va  2  s  .c  o m*/

    StringBuilder signatureBase = new StringBuilder(OAuthUtils.percentEncode(method));
    signatureBase.append("&");
    signatureBase.append(OAuthUtils.percentEncode(url));
    signatureBase.append("&");

    Map<String, String> treeMap = new TreeMap<String, String>(oauthParameters);
    treeMap.remove("oauth_signature");
    treeMap.remove("realm");

    boolean first = true;
    for (Map.Entry<String, String> entry : treeMap.entrySet()) {
        if (!first)
            signatureBase.append(OAuthUtils.percentEncode("&"));
        else
            first = false;

        signatureBase.append(OAuthUtils.percentEncode(entry.getKey() + "=" + entry.getValue()));
    }

    Mac mac = null;
    try {
        SecretKeySpec secretKeySpec = new SecretKeySpec((OAuthUtils.percentEncode(secret) + "&").getBytes(),
                algorithm);

        mac = Mac.getInstance(secretKeySpec.getAlgorithm());
        mac.init(secretKeySpec);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (log.isDebugEnabled()) {
        log.debug("signatureBaseString: " + signatureBase.toString());
    }

    byte[] bytes = mac.doFinal(signatureBase.toString().getBytes());
    byte[] encodedMacBytes = Base64.encodeBase64(bytes);

    return new String(encodedMacBytes);
}

From source file:org.apache.abdera2.common.security.KeyBase.java

protected byte[] hmac(byte[]... mat) {
    try {/*from   w ww  . java2s.c o  m*/
        Mac hmac = Mac.getInstance(alg);
        hmac.init(key);
        for (byte[] m : mat)
            hmac.update(m);
        return hmac.doFinal();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:ch.rasc.wampspring.cra.DefaultAuthenticationHandler.java

public static String generateHMacSHA256(final String key, final String data)
        throws InvalidKeyException, NoSuchAlgorithmException {
    Assert.notNull(key, "key is required");
    Assert.notNull(data, "data is required");

    final Mac hMacSHA256 = Mac.getInstance("HmacSHA256");
    byte[] hmacKeyBytes = key.getBytes(StandardCharsets.UTF_8);
    final SecretKeySpec secretKey = new SecretKeySpec(hmacKeyBytes, "HmacSHA256");
    hMacSHA256.init(secretKey);//w  ww . j  av a2s . co m
    byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
    byte[] res = hMacSHA256.doFinal(dataBytes);

    return DatatypeConverter.printBase64Binary(res);
}

From source file:cl.whyem.testsutilityproject.otpgenerator.KeyBase.java

protected byte[] hmac(byte[]... mat) {
    try {/*from  w ww.j  a va2 s. com*/
        Mac hmac = Mac.getInstance(alg);
        hmac.init(key);
        for (byte[] m : mat) {
            hmac.update(m);
        }
        return hmac.doFinal();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:com.github.bmadecoder.Authenticator.java

private void init(byte[] internalToken) throws InvalidKeyException {
    SecretKeySpec secretKeySpec = new SecretKeySpec(internalToken, "HmacSHA1");
    try {// w w  w  . ja v  a  2 s .c o  m
        mac = Mac.getInstance("HmacSHA1");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    mac.init(secretKeySpec);
}

From source file:org.apache.shindig.common.crypto.Crypto.java

/**
 * HMAC sha1/* ww  w  . j av a  2s .  com*/
 * 
 * @param key the key must be at least 8 bytes in length.
 * @param in byte array to HMAC.
 * @return the hash
 * 
 * @throws GeneralSecurityException
 */
public static byte[] hmacSha1(byte[] key, byte[] in) throws GeneralSecurityException {
    if (key.length < MIN_HMAC_KEY_LEN) {
        throw new GeneralSecurityException("HMAC key should be at least " + MIN_HMAC_KEY_LEN + " bytes.");
    }
    Mac hmac = Mac.getInstance(HMAC_TYPE);
    Key hmacKey = new SecretKeySpec(key, HMAC_TYPE);
    hmac.init(hmacKey);
    hmac.update(in);
    return hmac.doFinal();
}