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.system.seachgame.RequestHelper.java

/**
  * You must provide the three values below to initialize the helper.
  *//ww w  .  ja  va2s . c o  m
  * @param endpoint          Destination for the requests.
  * @param awsAccessKeyId    Your AWS Access Key ID
  * @param awsSecretKey      Your AWS Secret Key
  */
public static RequestHelper getInstance(String endpoint, String awsAccessKeyId, String awsSecretKey)
        throws IllegalArgumentException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {
    if (null == endpoint || endpoint.length() == 0) {
        throw new IllegalArgumentException("endpoint is null or empty");
    }
    if (null == awsAccessKeyId || awsAccessKeyId.length() == 0) {
        throw new IllegalArgumentException("awsAccessKeyId is null or empty");
    }
    if (null == awsSecretKey || awsSecretKey.length() == 0) {
        throw new IllegalArgumentException("awsSecretKey is null or empty");
    }

    RequestHelper instance = new RequestHelper();
    instance.endpoint = endpoint.toLowerCase();
    instance.awsAccessKeyId = awsAccessKeyId;
    instance.awsSecretKey = awsSecretKey;

    byte[] secretyKeyBytes = instance.awsSecretKey.getBytes(UTF8_CHARSET);
    instance.secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    instance.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    instance.mac.init(instance.secretKeySpec);

    return instance;
}

From source file:com.muk.ext.security.impl.DefaultNonceService.java

private String hash(String salt, String payload) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(salt.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);/*www  .  j a  v  a  2 s .com*/

    return Base64.encodeBase64URLSafeString(sha256_HMAC.doFinal(payload.getBytes()));
}

From source file:ch.docbox.elexis.UserDocboxPreferences.java

public static String getSSOSignature(String ts) {

    String username = getDocboxLoginID(false);

    String sha1Password = getSha1DocboxPassword();
    String sha1SecretKey = getSha1DocboxSecretKey();

    String message = username + ":" + ts + ":" + sha1Password; //$NON-NLS-1$ //$NON-NLS-2$
    try {/*from w  ww .j  a va 2  s. c o m*/
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey;
        signingKey = new SecretKeySpec(sha1SecretKey.getBytes("UTF-8"), "HmacSHA1"); //$NON-NLS-1$//$NON-NLS-2$

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");//$NON-NLS-1$
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8")); //$NON-NLS-1$

        // base64-encode the hmac
        // If desired, convert the digest into a string
        byte[] base64 = Base64.encodeBase64(rawHmac);
        return new String(base64);
    } catch (java.security.NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java

private static byte[] hmacSha256(final byte[] key, final String value) {
    try {/*from ww  w.  j ava2  s .  co  m*/
        final String algorithm = "HmacSHA256";
        final Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(utf8Bytes(value));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.scart.jcart.admin.aws.api.SignedRequestsHelper.java

/**
 * You must provide the three values below to initialize the helper.
 * /*from w ww .j a  va2 s. co m*/
 * @param endpoint
 *            Destination for the requests.
 * @param awsAccessKeyId
 *            Your AWS Access Key ID
 * @param awsSecretKey
 *            Your AWS Secret Key
 */
public static SignedRequestsHelper getInstance(String endpoint, String awsAccessKeyId, String awsSecretKey,
        String awsAssociateTagKey) throws IllegalArgumentException, UnsupportedEncodingException,
        NoSuchAlgorithmException, InvalidKeyException {
    if (null == endpoint || endpoint.length() == 0) {
        throw new IllegalArgumentException("endpoint is null or empty");
    }
    if (null == awsAccessKeyId || awsAccessKeyId.length() == 0) {
        throw new IllegalArgumentException("awsAccessKeyId is null or empty");
    }
    if (null == awsSecretKey || awsSecretKey.length() == 0) {
        throw new IllegalArgumentException("awsSecretKey is null or empty");
    }

    if (null == awsAssociateTagKey || awsAssociateTagKey.length() == 0) {
        throw new IllegalArgumentException("awsAssociateTagKey is null or empty");
    }

    SignedRequestsHelper instance = new SignedRequestsHelper();
    instance.endpoint = endpoint.toLowerCase();
    instance.awsAccessKeyId = awsAccessKeyId;
    instance.awsSecretKey = awsSecretKey;
    instance.awsAssociateTagKey = awsAssociateTagKey;

    byte[] secretyKeyBytes = instance.awsSecretKey.getBytes(UTF8_CHARSET);
    instance.secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    instance.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    instance.mac.init(instance.secretKeySpec);
    // instance.mac.init(instance.awsAssociateTagKey);

    return instance;
}

From source file:org.apache.sling.auth.xing.login.XingLoginUtil.java

private static byte[] hmac(final String message, final String secretKey, final String hashAlgorithm)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), hashAlgorithm);
    final Mac mac = Mac.getInstance(hashAlgorithm);
    mac.init(secretKeySpec);/*from   w  ww.  j  a v  a 2  s  .  co m*/
    return mac.doFinal(message.getBytes("UTF-8"));
}

From source file:nl.nn.adapterframework.pipes.HashPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    String message = (String) input;

    String authAlias = getAuthAlias();
    String secret = getSecret();//  w  w w .  ja  v a2  s. co m
    try {
        ParameterList parameterList = getParameterList();
        ParameterResolutionContext prc = new ParameterResolutionContext(message, session);
        ParameterValueList pvl = prc.getValues(parameterList);
        if (pvl != null) {
            Parameter authAliasParam = parameterList.findParameter("authAlias");
            if (authAliasParam != null)
                authAlias = (String) authAliasParam.getValue(pvl, prc);

            Parameter secretParam = parameterList.findParameter("secret");
            if (secretParam != null)
                secret = (String) secretParam.getValue(pvl, prc);
        }
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + "exception extracting authAlias", e);
    }

    CredentialFactory accessTokenCf = new CredentialFactory(authAlias, "", secret);
    String cfSecret = accessTokenCf.getPassword();

    if (cfSecret == null || cfSecret.isEmpty())
        throw new PipeRunException(this, getLogPrefix(session) + "empty secret, unable to hash");

    try {
        Mac mac = Mac.getInstance(getAlgorithm());

        SecretKeySpec secretkey = new SecretKeySpec(cfSecret.getBytes(getEncoding()), "algorithm");
        mac.init(secretkey);

        String hash = Base64.encodeBase64String(mac.doFinal(message.getBytes()));
        return new PipeRunResult(getForward(), hash);
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + "error creating hash", e);
    }
}

From source file:com.monitor.baseservice.utils.XCodeUtil.java

public static String hmacSha1(String value, String key) {
    try {/*from w ww. j  ava 2 s.  co  m*/
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

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

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

        return Base64.encodeBase64URLSafeString(rawHmac);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }
}

From source file:kcb.billerengine.utils.Utils.java

public static String computeToken(String key, String data) {
    String token = null;/*from   w ww .  jav  a 2 s .co  m*/
    try {
        SecretKey secretKey = null;
        byte[] keyBytes = key.getBytes("UTF-8");
        Mac mac = Mac.getInstance("HMACSHA256");
        secretKey = new SecretKeySpec(keyBytes, mac.getAlgorithm());
        mac.init(secretKey);
        byte[] text = data.getBytes("UTF-8");
        byte[] encodedText = mac.doFinal(text);

        token = new String(Base64.encodeBase64(encodedText)).trim();
    } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException ex) {
        LOG.error("ComputeToken error : " + ex);
    }

    return token;
}

From source file:aaf.vhr.crypto.GoogleAuthenticator.java

private static int verifyCode(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
    byte[] data = new byte[8];
    long value = t;
    for (int i = 8; i-- > 0; value >>>= 8) {
        data[i] = (byte) value;
    }//from   w  w  w  .  j a v  a 2s  .  c o m

    SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);

    int offset = hash[20 - 1] & 0xF;

    // We're using a long because Java hasn't got unsigned int.
    long truncatedHash = 0;
    for (int i = 0; i < 4; ++i) {
        truncatedHash <<= 8;
        // We are dealing with signed bytes:
        // we just keep the first byte.
        truncatedHash |= (hash[offset + i] & 0xFF);
    }

    truncatedHash &= 0x7FFFFFFF;
    truncatedHash %= 1000000;

    return (int) truncatedHash;
}