Example usage for javax.crypto Mac update

List of usage examples for javax.crypto Mac update

Introduction

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

Prototype

public final void update(ByteBuffer input) 

Source Link

Document

Processes input.remaining() bytes in the ByteBuffer input , starting at input.position() .

Usage

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

@Test
public void test01LoadTokenConfigProps() throws Exception {

    AuditLogCryptoTokenConfigData tokenConfig = hmac.getTokenConfig();
    CryptoToken token = CryptoTokenFactory.createCryptoToken(tokenConfig.getClassname(),
            tokenConfig.getProperties(), tokenConfig.getTokenData(), 1);

    token.activate(//from  ww w  .  ja v a 2s.co m
            ((String) tokenConfig.getProperties().get(CryptoToken.AUTOACTIVATE_PIN_PROPERTY)).toCharArray());
    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    byte[] signedData = hMac.doFinal();

    assertTrue(ArrayUtils.isEquals(signedData, signed));

}

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

protected byte[] hmac(byte[]... mat) {
    try {/*from  w w w  .jav  a 2 s .  c  om*/
        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:org.springframework.social.weibo.api.impl.TokenTemplate.java

/**
 * http://open.weibo.com/wiki/%E8%BD%BB%E5%BA%94%E7%94%A8%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97
 * @param signedRequest/* w  ww  . j  ava  2s. c  o  m*/
 * @param appSecret
 * @return
 */
private String parseSignedRequest(String signedRequest, String appSecret) {
    String tokenInfoValue = null;
    String[] tokens = StringUtils.split(signedRequest, "\\.", 2);
    // base64Token
    String base64Token = tokens[0];
    //  url encode/decode ??base64url ??
    // '+''/'??'-''_''=' ???base64?'='?
    int padding = (4 - base64Token.length() % 4);
    for (int i = 0; i < padding; i++) {
        base64Token += "=";
    }
    base64Token = StringUtils.replace(base64Token, "-", "+");
    base64Token = StringUtils.replace(base64Token, "_", "/");
    // base64Token1
    String token = tokens[1];
    SecretKey key = new SecretKeySpec(appSecret.getBytes(), ALGORITHM_HMACSHA256);
    try {
        Mac mac = Mac.getInstance(ALGORITHM_HMACSHA256);
        mac.init(key);
        mac.update(token.getBytes());
        byte[] macResult = mac.doFinal();
        String base64Token1 = Base64.encodeBase64String(macResult);
        // access token
        if (StringUtils.equals(base64Token, base64Token1)) {
            tokenInfoValue = new String(Base64.decodeBase64(token));
        }
    } catch (NoSuchAlgorithmException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    } catch (InvalidKeyException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    }
    return tokenInfoValue;
}

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);
    mac.update(str.getBytes("UTF-8"));
    return Base64.encodeBase64String(mac.doFinal()).replaceAll("\\s+", "");
}

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);/*from ww w.ja v a  2s  . 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:cl.whyem.testsutilityproject.otpgenerator.KeyBase.java

protected byte[] hmac(byte[]... mat) {
    try {/*w  w  w  . j  a v  a2 s  .co  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:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java

/**
 * Evaluate in a general context/*from w  ww  .  java  2s . c o  m*/
 */
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:org.kaaproject.kaa.server.verifiers.twitter.verifier.OAuthHeaderBuilder.java

private String generateSignature(String signatureBase, String accessTokenSecret)
        throws InvalidKeyException, NoSuchAlgorithmException {

    Mac mac = Mac.getInstance(ENCRYPTION_ALGO);
    mac.init(new SecretKeySpec((CONSUMER_SECRET + "&" + accessTokenSecret).getBytes(), ENCRYPTION_ALGO));
    mac.update(signatureBase.getBytes());
    byte[] res = mac.doFinal();
    String signature = new String(Base64.encodeBase64(res)).trim();

    return signature;
}

From source file:test.unit.be.fedict.eid.applet.service.UserIdentifierUtilTest.java

@Test
public void testHMacSha1() throws Exception {
    SecretKey macKey = new SecretKeySpec("1234".getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance(macKey.getAlgorithm());
    mac.init(macKey);//from  w w  w .  j a  v a  2s  .  co  m

    byte[] data = "hello world".getBytes();

    mac.update(data);
    byte[] resultHMac = mac.doFinal();

    LOG.debug("size result HMAC-SHA1: " + resultHMac.length);
    String resultHex = new String(Hex.encodeHex(resultHMac)).toUpperCase();
    LOG.debug("result HMAC-SHA1 HEX: " + resultHex);
}

From source file:com.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java

public String getChecksumBy(final String key)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()));
    mac.update((cardToken + mctTransAuthId + ocTransAuthId
            + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(mac.doFinal());
}