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:hudson.plugins.sauce_ondemand.PluginImpl.java

/**
 * Creates a HMAC token which is used as part of the Javascript inclusion that embeds the Sauce results
 *
 * @param username  the Sauce user id//from  w  ww  . j a v  a  2s .  c  o m
 * @param accessKey the Sauce access key
 * @param jobId     the Sauce job id
 * @return the HMAC token
 * @throws java.security.NoSuchAlgorithmException
 *
 * @throws java.security.InvalidKeyException
 *
 * @throws java.io.UnsupportedEncodingException
 *
 */
public String calcHMAC(String username, String accessKey, String jobId)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    Calendar calendar = Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    String key = username + ":" + accessKey + ":" + format.format(calendar.getTime());
    byte[] keyBytes = key.getBytes();
    SecretKeySpec sks = new SecretKeySpec(keyBytes, HMAC_KEY);
    Mac mac = Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);
    byte[] hmacBytes = mac.doFinal(jobId.getBytes());
    byte[] hexBytes = new Hex().encode(hmacBytes);
    return new String(hexBytes, "ISO-8859-1");
}

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 a v a  2 s  .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:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java

protected String hashRequestBody(HttpServletRequest request, SecretKey secretKey)
        throws IOException, ServletException {
    final byte[] result;
    try {/*w w w . j a v  a 2s.co 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:com.restswitch.controlpanel.MainActivity.java

private void sendDevice(String devid, String host, String msg, String pwdHash) {
    try {//w  ww .  j  av  a  2s.  c o m
        final long utcStart = System.currentTimeMillis();
        String b32UntilUtc = B32Coder.encodeDatetimeNow(8000); // valid for 8 sec
        String method = "PUT";
        String uri = ("/pub/" + devid);
        String val = (method + uri + msg + b32UntilUtc);

        String b64Hash = null;
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(new javax.crypto.spec.SecretKeySpec(pwdHash.getBytes("utf-8"), "HmacSHA256"));
            byte[] hash = hmacSha256.doFinal(val.getBytes("UTF-8"));
            b64Hash = Base64.encodeToString(hash, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
        } catch (Exception ex) {
            alertError("Invalid password, verify app settings.");
            return;
        }

        Properties headers = new Properties();
        headers.setProperty("x-body", msg);
        headers.setProperty("x-auth1", b32UntilUtc);
        headers.setProperty("x-auth2", b64Hash);

        AjaxTask ajaxTask = new AjaxTask();
        ajaxTask.putAjaxEventHandler(this);
        //            // use to set a custom ca
        //            boolean rc = ajaxTask.putRootCaCert(rootCa, true);
        //            if(!rc) {
        //                alertError("Failed to initialize network task.");
        //                return;
        //            }
        AjaxTask.Data data = new AjaxTask.Data();
        data.param1 = devid;
        data.param2 = utcStart;
        ajaxTask.invoke("http", host, uri, method, headers, msg, data);
    } catch (Exception ex) {
        alertError(ex.getMessage());
    }
}

From source file:com.thoughtworks.go.server.controller.AgentRegistrationController.java

private Mac hmac() {
    if (mac == null) {
        try {// w w  w  .j a  v  a 2  s  . co  m
            mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(
                    goConfigService.serverConfig().getTokenGenerationKey().getBytes(), "HmacSHA256");
            mac.init(secretKey);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
    return mac;
}

From source file:ch.cyberduck.core.sftp.openssh.OpenSSHHostKeyVerifier.java

private static byte[] hmacSha1Hash(byte[] salt, String hostname) throws IOException {
    try {//from   www. ja v  a2  s.  co m
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(salt, 0, salt.length, mac.getAlgorithm()));
        mac.update(hostname.getBytes());
        return mac.doFinal();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:nl.esciencecenter.osmium.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data/* w  w w  .  j a va 2s .  co m*/
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes(StandardCharsets.US_ASCII));
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:example.DecrypterException.java

/**
 * Performs the decryption algorithm./*from  ww w . j  a v a 2 s  . co m*/
 *
 * This method decrypts the ciphertext using the encryption key and verifies
 * the integrity bits with the integrity key. The encrypted format is:
 * {initialization_vector (16 bytes)}{ciphertext}{integrity (4 bytes)}
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-
 * hyperlocal,
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt
 * -price and https://support.google.com/adxbuyer/answer/3221407?hl=en have
 * more details about the encrypted format of hyperlocal, winning price,
 * IDFA, hashed IDFA and Android Advertiser ID.
 */
public static byte[] decrypt(byte[] ciphertext, SecretKey encryptionKey, SecretKey integrityKey)
        throws DecrypterException {
    try {
        // Step 1. find the length of initialization vector and clear text.
        final int plaintext_length = ciphertext.length - INITIALIZATION_VECTOR_SIZE - SIGNATURE_SIZE;
        if (plaintext_length < 0) {
            throw new RuntimeException("The plain text length can't be negative.");
        }
        System.out.println(Arrays.toString(ciphertext));
        System.out.println(byte2hex(ciphertext));
        System.out.println(ciphertext.length);
        System.out.println(plaintext_length);

        byte[] iv = Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE);

        // Step 2. recover clear text
        final Mac hmacer = Mac.getInstance("HmacSHA1");
        hmacer.init(encryptionKey);

        final int ciphertext_end = INITIALIZATION_VECTOR_SIZE + plaintext_length;
        final byte[] plaintext = new byte[plaintext_length];
        boolean add_iv_counter_byte = true;
        for (int ciphertext_begin = INITIALIZATION_VECTOR_SIZE, plaintext_begin = 0; ciphertext_begin < ciphertext_end;) {
            System.out.println("=====> FOR:");
            hmacer.reset();
            hmacer.init(encryptionKey);
            System.out.println("iv: " + byte2hex(iv));
            final byte[] pad = hmacer.doFinal(iv);
            System.out.println("pad: " + byte2hex(pad) + "  len(pad): " + pad.length);
            Base64 encoder = new Base64();
            String pad_base64 = new String(encoder.encode(pad));
            System.out.println("pad Base64: " + pad_base64);

            int i = 0;
            while (i < BLOCK_SIZE && ciphertext_begin != ciphertext_end) {
                plaintext[plaintext_begin++] = (byte) (ciphertext[ciphertext_begin++] ^ pad[i++]);
            }

            if (!add_iv_counter_byte) {
                final int index = iv.length - 1;
                add_iv_counter_byte = ++iv[index] == 0;
            }

            if (add_iv_counter_byte) {
                add_iv_counter_byte = false;
                iv = Arrays.copyOf(iv, iv.length + 1);
            }
        }
        System.out.println("plaintext: " + byte2hex(plaintext));

        // Step 3. Compute integrity hash. The input to the HMAC is
        // clear_text
        // followed by initialization vector, which is stored in the 1st
        // section
        // or ciphertext.
        hmacer.reset();
        hmacer.init(integrityKey);
        hmacer.update(plaintext);
        hmacer.update(Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE));
        final byte[] computedSignature = Arrays.copyOf(hmacer.doFinal(), SIGNATURE_SIZE);
        final byte[] signature = Arrays.copyOfRange(ciphertext, ciphertext_end,
                ciphertext_end + SIGNATURE_SIZE);
        if (!Arrays.equals(signature, computedSignature)) {
            throw new DecrypterException("Signature mismatch.");
        }
        return plaintext;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HmacSHA1 not supported.", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Key is invalid for this purpose.", e);
    }
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

/**
 * @throws NoSuchAlgorithmException/*ww w . j  av  a  2s .  co  m*/
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws IllegalStateException
 * @throws NullPointerException if <code>tokenFile</code> is
 *             <code>null</code>.
 */
TokenStore(final File tokenFile, final long sessionTimeout, final boolean fastSeed)
        throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {

    if (tokenFile == null) {
        throw new NullPointerException("tokenfile");
    }

    this.random = SecureRandom.getInstance(SHA1PRNG);
    this.ttl = sessionTimeout;
    this.tokenFile = tokenFile;
    this.tmpTokenFile = new File(tokenFile + ".tmp");

    // prime the secret keys from persistence
    loadTokens();

    // warm up the crypto API
    if (fastSeed) {
        random.setSeed(getFastEntropy());
    } else {
        log.info("Seeding the secure random number generator can take "
                + "up to several minutes on some operating systems depending "
                + "upon environment factors. If this is a problem for you, "
                + "set the system property 'java.security.egd' to "
                + "'file:/dev/./urandom' or enable the Fast Seed Generator " + "in the Web Console");
    }
    byte[] b = new byte[20];
    random.nextBytes(b);
    final SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1);
    final Mac m = Mac.getInstance(HMAC_SHA1);
    m.init(secretKey);
    m.update(UTF_8.getBytes(UTF_8));
    m.doFinal();
}

From source file:com.monarchapis.client.authentication.HawkV1RequestProcessor.java

private String getHawkHeader(BaseClient<?> client, String accessToken, String payloadHash, String extData) {
    try {//from w ww  .j  a v a  2 s.c o  m
        StringBuilder sb = new StringBuilder();

        long ts = System.currentTimeMillis() / 1000;
        String nonce = RandomStringUtils.randomAlphanumeric(6);

        URI uri = URI.create(client.getUrl());

        sb.append("hawk.1.header\n");
        sb.append(ts);
        sb.append("\n");
        sb.append(nonce);
        sb.append("\n");
        sb.append(client.getMethod());
        sb.append("\n");
        sb.append(uri.getRawPath());
        sb.append("\n");
        sb.append(uri.getHost());
        sb.append("\n");
        sb.append(uri.getPort());
        sb.append("\n");

        if (payloadHash != null) {
            sb.append(payloadHash);
        }

        sb.append("\n");

        if (extData != null) {
            sb.append(extData);
        }

        sb.append("\n");

        if (accessToken != null) {
            sb.append(apiKey);
            sb.append("\n");
        }

        String stringData = sb.toString();

        String algo = HmacUtils.getHMacAlgorithm(algorithm);
        byte[] key = sharedSecret.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(key, algo);

        Mac mac256 = Mac.getInstance(algo);
        mac256.init(signingKey);

        // compute the hmac on input data bytes
        byte[] hash = mac256.doFinal(stringData.getBytes("UTF-8"));
        String mac = Base64.encodeBase64String(hash);

        return "Hawk id=\"" + (accessToken != null ? accessToken : apiKey) + "\", ts=\"" + ts + "\", nonce=\""
                + nonce + "\"" + (payloadHash != null ? ", hash=\"" + payloadHash + "\"" : "")
                + (extData != null ? ", ext=\"" + extData + "\"," : "") + ", mac=\"" + mac + "\""
                + (accessToken != null ? ", app=\"" + apiKey + "\"" : "");
    } catch (Exception e) {
        throw new RuntimeException("Could not create hawk header", e);
    }
}