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.petercho.Encoder.java

public static byte[] getHmac(String secretKey, String payload, String hmacType) {
    final Mac mac;
    byte[] hmac;/*from  w w w  .  ja v a2  s . co  m*/
    try {
        final byte[] secretKeyBytes;
        if (secretKey == null) {
            secretKeyBytes = new byte[] { 0 };
        } else {
            secretKeyBytes = secretKey.getBytes(DEFAULT_ENCODING);
        }
        if (payload == null) {
            payload = "";
        }
        SecretKeySpec keySpec = new SecretKeySpec(secretKeyBytes, hmacType);
        mac = Mac.getInstance(hmacType);
        mac.init(keySpec);
        hmac = mac.doFinal(payload.getBytes(DEFAULT_ENCODING));
    } catch (NoSuchAlgorithmException e) {
        String msg = "An error occurred initializing algorithm '" + hmacType + "', e: " + e;
        throw new IllegalStateException(msg, e);
    } catch (InvalidKeyException e) {
        String msg = "An error occurred initializing key, e: " + e;
        throw new IllegalStateException(msg, e);
    } catch (UnsupportedEncodingException e) {
        String msg = "Invalid encoding, e: " + e;
        throw new IllegalStateException(msg, e);
    }
    return hmac;
}

From source file:com.ideas.api.client.services.members.OAuth2Services.java

License:asdf

private static String computeSignature(String baseString, String keyString)
        throws GeneralSecurityException, UnsupportedEncodingException {

    SecretKey secretKey = null;// w w  w .  j  a va 2  s.  c o m

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(secretKey);

    byte[] text = baseString.getBytes();

    return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}

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

/**
 * Gives back a non-reversible citizen identifier (NRCID).
 * /*from   w w  w.  j  ava2s .  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:com.QuarkLabs.BTCeClientJavaFX.networking.AuthRequest.java

public JSONObject makeRequest(String method, Map<String, String> arguments)
        throws UnsupportedEncodingException {
    if (method == null) {
        return null;
    }/* www . jav  a2 s . c o m*/
    if (arguments == null) {
        arguments = new HashMap<>();
    }
    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }
    StringBuilder out = new StringBuilder();
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Key", key);
        String sign = byteArrayToHexString(mac.doFinal(postData.getBytes("UTF-8")));
        urlConnection.setRequestProperty("Sign", sign);
        urlConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
            rd.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new JSONObject(out.toString());
}

From source file:com.coinkite.CoinkiteSigningRequestInterceptor.java

public String[] createSigAndTimestamp(String url) throws NoSuchAlgorithmException, InvalidKeyException {
    String apiSecret = getApiSecret();
    SecretKeySpec signingKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), HMAC_SHA512_ALG);

    Mac mac = Mac.getInstance(HMAC_SHA512_ALG);
    mac.init(signingKey);/*w ww .j a v a  2s  .co m*/

    String ts = getDateTime().format(ISO_DATE_TIME);

    byte[] bytes = mac.doFinal(getData(url, ts));
    String encoded = Hex.encodeHexString(bytes);

    return new String[] { encoded, ts };
}

From source file:com.example.android.vault.EncryptedDocument.java

/**
 * Create an encrypted document.//from  www .j  a  v  a 2  s. c o  m
 *
 * @param docId the expected {@link Document#COLUMN_DOCUMENT_ID} to be
 *              validated when reading metadata.
 * @param file  location on disk where the encrypted document is stored. May
 *              not exist yet.
 */
public EncryptedDocument(long docId, File file, SecretKey dataKey, SecretKey macKey)
        throws GeneralSecurityException {
    mRandom = new SecureRandom();
    mCipher = Cipher.getInstance("AES/CTR/NoPadding");
    mMac = Mac.getInstance("HmacSHA256");

    if (dataKey.getEncoded().length != DATA_KEY_LENGTH) {
        throw new IllegalArgumentException("Expected data key length " + DATA_KEY_LENGTH);
    }
    if (macKey.getEncoded().length != MAC_KEY_LENGTH) {
        throw new IllegalArgumentException("Expected MAC key length " + MAC_KEY_LENGTH);
    }

    mDocId = docId;
    mFile = file;
    mDataKey = dataKey;
    mMacKey = macKey;
}

From source file:za.co.bronkode.jwtbroker.Tokenizer.java

public static String GetSignature(String header, String claim) {
    try {/*from  w w  w .j  av a 2  s .c  o m*/

        StringBuilder sb = new StringBuilder(header);
        sb.append(".");
        sb.append(claim);
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKey key = new SecretKeySpec(privateKey.getBytes(), "HmacSHA256");

        mac.init(key);
        String signature = Base64.getEncoder().encodeToString(mac.doFinal(sb.toString().getBytes()));
        return signature;
    } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
        Logger.getLogger(Tokenizer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

/**
 * Creates the signature from the timestamp using the sharedKey.  This same method will be used
 * on the server and the results compared to authenticate the request.
 * /*w  w  w.  j  a  va 2s.c om*/
 * @param timeStamp
 * @return
 */
private static String getSignature(String timeStamp) {
    if (sharedKey != null)
        try {
            byte[] data = timeStamp.getBytes(ENCODING_FORMAT);
            Mac mac = Mac.getInstance(SIGNATURE_METHOD);
            mac.init(new SecretKeySpec(sharedKey.getBytes(ENCODING_FORMAT), SIGNATURE_METHOD));
            char[] signature = Hex.encodeHex(mac.doFinal(data));
            return new String(signature);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    return "Error in getSignature()";
}

From source file:Networking.Server.java

public static String calculateHMAC(String data, byte[] key) {
    Mac mac = null;/*w  w w  .j ava  2  s .  com*/
    byte[] res = null;
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
        mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        res = (mac.doFinal(data.getBytes()));

    } catch (InvalidKeyException | NoSuchAlgorithmException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }
    return toHexString(res);
}

From source file:org.apache.http.contrib.auth.AWSScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data//from  w  w  w. j a va 2 s  .  c  o m
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws RuntimeException
 *             when signature generation fails
 */
private static String calculateRFC2104HMAC(final String data, final String key) throws AuthenticationException {
    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
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // base64-encode the hmac
        return Base64.encodeBase64String(rawHmac);

    } catch (InvalidKeyException ex) {
        throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new AuthenticationException(HMAC_SHA1_ALGORITHM + " algorithm is not supported", ex);
    }
}