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.jivesoftware.sdk.service.filter.JiveAuthorizationValidator.java

@Nonnull
private String sign(@Nonnull String str, @Nonnull String clientSecret, @Nonnull String algorithm)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    byte[] secret = Base64.decodeBase64(clientSecret);
    SecretKeySpec secretKeySpec = new SecretKeySpec(secret, algorithm);
    Mac mac = Mac.getInstance(algorithm);
    mac.init(secretKeySpec);//from  w  w w.j a v  a2  s . c  om
    mac.update(str.getBytes("UTF-8"));
    return Base64.encodeBase64String(mac.doFinal()).replaceAll("\\s+", "");
}

From source file:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java

/**
 * Evaluate in a general context/*from www  .  j  a  v  a2s  .  com*/
 */
public Item evaluateItem(XPathContext xpathContext) throws XPathException {
    final String key = argument[0].evaluateAsString(xpathContext).toString();
    final String data = argument[1].evaluateAsString(xpathContext).toString();
    final String originalAlgorithmString = argument[2].evaluateAsString(xpathContext).toString();
    final String algorithm = "Hmac" + originalAlgorithmString.replaceAll("-", "");
    final String encoding = argument != null && argument.length >= 4
            ? argument[3].evaluateAsString(xpathContext).toString()
            : kBASE64;

    if (!kSUPPORTED_ALG.contains(originalAlgorithmString)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException(
                "Unsupported algorithm '" + originalAlgorithmString + "'", xformsElement.getTarget(), this));
    }

    if (!kSUPPORTED_ENCODINGS.contains(encoding)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'",
                xformsElement.getTarget(), this));
    }

    try {
        // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104
        // In practice, you would save this key.
        SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), algorithm);

        // Create a MAC object using HMAC-MD5 and initialize with kesaxoniay
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        mac.update(data.getBytes("utf-8"));

        byte[] digest = mac.doFinal();

        final BinaryEncoder encoder;
        if ("base64".equals(encoding)) {
            encoder = new Base64(digest.length, "".getBytes(), false);
        } else {
            encoder = new Hex();
        }

        return new StringValue(new String(encoder.encode(digest), "ASCII"));

    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(e);
    } catch (UnsupportedEncodingException e) {
        throw new XPathException(e);
    } catch (EncoderException e) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(
                new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this));
    } catch (InvalidKeyException e) {
        throw new XPathException(e);
    }

}

From source file:mitm.common.security.otp.HMACOTPGenerator.java

private Mac createMAC(byte[] secret) throws OTPException {

    try {//from  w w w  . java 2 s. c  om
        Mac mac = securityFactory.createMAC(algorithm);

        SecretKeySpec keySpec = new SecretKeySpec(secret, "raw");

        mac.init(keySpec);

        return mac;
    } catch (NoSuchAlgorithmException e) {
        throw new OTPException(e);
    } catch (NoSuchProviderException e) {
        throw new OTPException(e);
    } catch (InvalidKeyException e) {
        throw new OTPException(e);
    }
}

From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java

@Before
public void createHmacConfig() throws Exception {
    log.trace(">setUp()");

    tokenConfigData = new AuditLogCryptoTokenConfigData();
    tokenConfigData.setClassname(SoftCryptoToken.class.getName());
    Properties props = new Properties();
    props.setProperty(CryptoToken.AUTOACTIVATE_PIN_PROPERTY, tokenPin);

    CryptoToken token = CryptoTokenFactory.createCryptoToken(SoftCryptoToken.class.getName(), props, null, 1);
    token.activate(tokenPin.toCharArray());
    token.generateKey("HmacSHA1", 256, keyAlias);

    tokenConfigData.setProperties(props);

    hmac = new HmacLogManagementData();
    hmac.setAlgorithm(algorithm);//ww  w . ja  v  a  2  s .c o m
    hmac.setKeyLabel(keyAlias);
    hmac.setFrequency(0l);
    hmac.setTokenConfig(tokenConfigData);

    byte[] tokenData = token.getTokenData();
    tokenConfigData.setTokenData(tokenData);

    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    signed = hMac.doFinal();

    log.trace("<setUp()");
}

From source file:com.pliu.powerbiembed.ReportController.java

private String HMAC256EncryptBase64UrlEncode(String str, String accessKey) throws Exception {
    byte[] key = accessKey.getBytes("UTF-8");
    byte[] strBytes = str.getBytes("UTF-8");
    Mac enc = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(key, "HmacSHA256");
    enc.init(secret_key);
    byte[] hashBytes = enc.doFinal(strBytes);
    String b64Str = new String(Base64.encodeBase64(hashBytes));
    return b64Str.replace('/', '_').replace('+', '-').replaceAll("[=]+$", "");
}

From source file:com.torchmind.authenticator.AbstractTokenGenerator.java

/**
 * Generates a code based on a secret key and challenge.
 *
 * @param secretKey a secret key./*from  www .  ja  v a 2 s .c  om*/
 * @param challenge a challenge.
 * @return a code.
 */
@NonNull
protected String generateCode(@NonNull SecretKey secretKey, @NonNull byte[] challenge) {
    try {
        Mac mac = Mac.getInstance("Hmac" + this.algorithm.name());
        mac.init(secretKey);

        byte[] hash = mac.doFinal(challenge);
        int offset = hash[hash.length - 1] & 0x0F;

        ByteBuffer buffer = ByteBuffer.allocate(4).put(hash, offset, 4);
        buffer.flip();

        return String.format("%0" + this.digits + "d", (buffer.getInt() & 0x7FFFFFFF) % this.digitModulo);
    } catch (NoSuchAlgorithmException ex) {
        throw new UnsupportedOperationException(
                "The specified algorithm is not supported by this Java VM implementation: " + ex.getMessage(),
                ex);
    } catch (InvalidKeyException ex) {
        throw new IllegalArgumentException("Invalid shared secret: " + ex.getMessage(), ex);
    }
}

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

protected String hashRequestBody(HttpServletRequest request, SecretKey secretKey)
        throws IOException, ServletException {
    final byte[] result;
    try {/*from w  ww .j a v  a  2  s  . c o  m*/
        final Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        result = mac.doFinal(IOUtils.toByteArray(request.getInputStream()));
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException(e);
    } catch (InvalidKeyException e) {
        throw new ServletException(e);
    }

    return new String(Hex.encodeHex(result));
}

From source file:net.groupbuy.plugin.yeepay.YeepayPlugin.java

/**
 * Hmac/*w ww . j av a2 s . c om*/
 * 
 * @param value
 *            
 * @param key
 *            
 * @return 
 */
private String hmacDigest(String value, String key) {
    try {
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacMD5"));
        byte[] bytes = mac.doFinal(value.getBytes("UTF-8"));

        StringBuffer digest = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                digest.append("0");
            }
            digest.append(hex);
        }
        return digest.toString();
    } catch (Exception e) {
        return null;
    }
}

From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java

private String getHMAC256(final String input, final String secret) {
    String temp = null;//w w w. j av  a  2s .  co  m
    final SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        // update method adds the given byte to the Mac's input data. 
        mac.update(input.getBytes());
        final byte[] m = mac.doFinal();
        // The base64-encoder in Commons Codec
        temp = base64Encode(m);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return temp;
}

From source file:com.zegoggles.smssync.XOAuthConsumer.java

private String generateSig(HttpRequest request, HttpParameters requestParameters) throws Exception {
    String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
    byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);

    SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);

    String sbs = new SignatureBaseString(request, requestParameters).generate();
    return base64(mac.doFinal(sbs.getBytes(OAuth.ENCODING)));
}