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:Main.java

/**
 * Compute the HMAC with SHA-256 of data, as defined in
 * http://tools.ietf.org/html/rfc2104#section-2 .
 * @param key The key byte array./*from   w  ww  .  j  a v a 2  s . c  om*/
 * @param data The input byte buffer. This does not change the position.
 * @return The HMAC result.
 */
public static byte[] computeHmacWithSha256(byte[] key, ByteBuffer data) {
    final String algorithm = "HmacSHA256";
    Mac mac;
    try {
        mac = Mac.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
        // Don't expect this to happen.
        throw new Error("computeHmac: " + algorithm + " is not supported: " + ex.getMessage());
    }

    try {
        mac.init(new SecretKeySpec(key, algorithm));
    } catch (InvalidKeyException ex) {
        // Don't expect this to happen.
        throw new Error("computeHmac: Can't init " + algorithm + " with key: " + ex.getMessage());
    }
    int savePosition = data.position();
    mac.update(data);
    data.position(savePosition);
    return mac.doFinal();
}

From source file:be.fedict.eid.applet.service.impl.UserIdentifierUtil.java

/**
 * Gives back a non-reversible citizen identifier (NRCID).
 * //from w  w w. ja  v a 2s .c  o  m
 * @param userId
 *            the primary user identifier, i.e. the national registry
 *            number.
 * @param orgId
 *            the optional organization identifier.
 * @param appId
 *            the optional application identifier.
 * @param secret
 *            the application specific secret. Should be at least 128 bit
 *            long. Encoded in hexadecimal format.
 * @return
 */
public static String getNonReversibleCitizenIdentifier(String userId, String orgId, String appId,
        String secret) {
    if (null == secret) {
        throw new IllegalArgumentException("secret key is null");
    }
    /*
     * Avoid XML formatting issues introduced by some web.xml XML editors.
     */
    secret = secret.trim();
    if (null != orgId) {
        orgId = orgId.trim();
    } else {
        LOG.warn("it is advised to use an orgId");
    }
    if (null != appId) {
        appId = appId.trim();
    } else {
        LOG.warn("it is advised to use an appId");
    }

    /*
     * Decode the secret key.
     */
    byte[] secretKey;
    try {
        secretKey = Hex.decodeHex(secret.toCharArray());
    } catch (DecoderException e) {
        LOG.error("secret is not hexadecimal encoded: " + e.getMessage());
        throw new IllegalArgumentException("secret is not hexadecimal encoded");
    }
    if ((128 / 8) > secretKey.length) {
        /*
         * 128 bit is seen as secure these days.
         */
        LOG.warn("secret key is too short");
        throw new IllegalArgumentException("secret key is too short");
    }

    /*
     * Construct the HMAC input sequence.
     */
    String input = userId;
    if (null != appId) {
        input += appId;
    }
    if (null != orgId) {
        input += orgId;
    }
    byte[] inputData = input.getBytes();

    SecretKey macKey = new SecretKeySpec(secretKey, HMAC_ALGO);
    Mac mac;
    try {
        mac = Mac.getInstance(macKey.getAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HMAC algo not available: " + e.getMessage());
    }
    try {
        mac.init(macKey);
    } catch (InvalidKeyException e) {
        LOG.error("invalid secret key: " + e.getMessage(), e);
        throw new RuntimeException("invalid secret");
    }
    mac.update(inputData);
    byte[] resultHMac = mac.doFinal();
    String resultHex = new String(Hex.encodeHex(resultHMac)).toUpperCase();
    return resultHex;
}

From source file:lucee.commons.io.res.type.s3.S3.java

private static byte[] HMAC_SHA1(String key, String message, String charset)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec sks = new SecretKeySpec(key.getBytes(charset), "HmacSHA1");
    Mac mac = Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);//from   w  w  w  .j a  v  a2  s . c  o m
    mac.update(message.getBytes(charset));
    return mac.doFinal();

}

From source file:com.cloud.servlet.ConsoleProxyServlet.java

public static String genAccessTicket(String host, String port, String sid, String tag,
        Date normalizedHashTime) {
    String params = "host=" + host + "&port=" + port + "&sid=" + sid + "&tag=" + tag;

    try {/*from   w w w. j a v a  2s .co m*/
        Mac mac = Mac.getInstance("HmacSHA1");

        long ts = normalizedHashTime.getTime();
        ts = ts / 60000; // round up to 1 minute
        String secretKey = _ms.getHashKey();

        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(params.getBytes());
        mac.update(String.valueOf(ts).getBytes());

        byte[] encryptedBytes = mac.doFinal();

        return Base64.encodeBase64String(encryptedBytes);
    } catch (Exception e) {
        s_logger.error("Unexpected exception ", e);
    }
    return "";
}

From source file:net.sf.xfd.provider.PublicProvider.java

public static @Nullable Uri publicUri(Context context, CharSequence path, String mode) {
    // XXX suspect coversion
    final String pathString = path.toString();

    final int modeInt = ParcelFileDescriptor.parseMode(mode);

    final Key key = getSalt(context);

    if (key == null) {
        return null;
    }// w w w .  j  a va  2 s.  c o m

    final Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, 1);
    final long l = c.getTimeInMillis();

    final byte[] encoded;
    try {
        final Mac hash = Mac.getInstance("HmacSHA1");
        hash.init(key);

        final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16),
                (byte) (modeInt >> 8), (byte) modeInt, };
        hash.update(modeBits);

        final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40),
                (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, };
        hash.update(expiryDate);

        encoded = hash.doFinal(pathString.getBytes());
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new AssertionError("Error while creating a hash: " + e.getMessage(), e);
    }

    final String packageName = context.getPackageName();

    final Uri.Builder b = new Uri.Builder().scheme(SCHEME_CONTENT).authority(packageName + AUTHORITY_SUFFIX);

    if (!"r".equals(mode)) {
        b.appendQueryParameter(URI_ARG_MODE, mode);
    }

    return b.path(pathString).appendQueryParameter(URI_ARG_EXPIRY, String.valueOf(l))
            .appendQueryParameter(URI_ARG_COOKIE, encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING))
            .build();
}

From source file:org.apache.ws.security.message.token.UsernameToken.java

/**
 * P_hash as defined in RFC 2246 for TLS.
 * /* ww  w  . j av a  2 s .c om*/
 * @param secret is the key for the HMAC
 * @param seed the seed value to start the generation - A(0)
 * @param mac the HMAC algorithm
 * @param required number of bytes to generate
 * @return a byte array that contains a secret key
 * @throws Exception
 */
private static byte[] P_hash(byte[] secret, byte[] seed, Mac mac, int required) throws Exception {
    byte[] out = new byte[required];
    int offset = 0, tocpy;
    byte[] A, tmp;
    //
    // A(0) is the seed
    //
    A = seed;
    SecretKeySpec key = new SecretKeySpec(secret, "HMACSHA1");
    mac.init(key);
    while (required > 0) {
        mac.update(A);
        A = mac.doFinal();
        mac.update(A);
        mac.update(seed);
        tmp = mac.doFinal();
        tocpy = min(required, tmp.length);
        System.arraycopy(tmp, 0, out, offset, tocpy);
        offset += tocpy;
        required -= tocpy;
    }
    return out;
}

From source file:com.moha.demo.utils.Hashsalt.java

public String encrypt(String password) {
    String algorithm = EnvUtils.getProperty("algorithm");
    String keyString = EnvUtils.getProperty("keyString");
    SecretKey key = new SecretKeySpec(keyString.getBytes(), algorithm);

    try {/*from   w ww  . j  a  va 2s.co  m*/
        Mac m = Mac.getInstance(algorithm);
        m.init(key);
        m.update(password.getBytes());
        byte[] mac = m.doFinal();
        return toHexString(mac);
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    return StringUtils.EMPTY;
}

From source file:com.twosigma.beakerx.security.HashedMessageAuthenticationCode.java

public String signBytes(List<byte[]> msg) {
    try {//  ww w.ja v  a 2 s.c o m
        final Mac mac = Mac.getInstance(TYPE);
        mac.init(spec);
        msg.forEach(it -> mac.update(it));
        byte[] digest = mac.doFinal();
        return toHex(digest);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(INVALID_HMAC_EXCEPTION, e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:mitm.application.djigzo.james.PortalInvitationValidator.java

/**
 * returns the calculated MAC/*w w w .j  a va2s .c o m*/
 */
public String calulateMAC(String key) throws ValidatorException {
    Check.notNull(key, "key");

    if (StringUtils.isEmpty(email)) {
        throw new ValidatorException("email is not set");
    }

    if (timestamp == null) {
        throw new ValidatorException("timestamp is not set");
    }

    Mac mac = createMAC(key);

    mac.update(UNIQUE_ID);
    mac.update(MiscStringUtils.toUTF8Bytes(email));
    mac.update(timestamp.byteValue());

    byte[] hmac = mac.doFinal();

    return Base32.encode(hmac);
}

From source file:signature.common.signature.SignatureCalculator.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * //  w  w  w .j a va  2s . c  om
 * @param data
 *            The data to be signed.
 * @param key
 *            The signing key, a.k.a. the AWS secret key.
 * @return The base64-encoded RFC 2104-compliant HMAC signature.
 * @throws java.security.SignatureException
 *             when signature generation fails
 */
public byte[] calculateRFC2104HMAC(byte[] data, String key) throws SignatureException {
    byte[] result = null;

    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

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

        // compute the hmac on input data bytes
        mac.update(data);
        byte[] rawHmac = mac.doFinal();

        // base64-encode the hmac
        result = Base64.encodeBase64(rawHmac);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC: ", e);
    }

    return result;
}