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:org.dasein.cloud.virtustream.VirtustreamMethod.java

private byte[] calculateHmac(String data, String key) throws SignatureException {
    try {//from  ww  w .j  a  v a  2  s. c o  m
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        return mac.doFinal(data.getBytes());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}

From source file:com.tcs.ebw.security.EBWSecurity.java

public void computeMac(String fileName) throws NoSuchAlgorithmException, InvalidKeyException

        , FileNotFoundException, IOException, NoSuchPaddingException {

    Mac mac = Mac.getInstance(EBWConstants.ENCRYPTION_MAC_ALGORITHM);

    mac.init(generateKeyForSymmetric());

    FileInputStream fis = new FileInputStream(fileName);

    byte[] dataBytes = new byte[1024];

    int nread = fis.read(dataBytes);

    while (nread > 0) {

        mac.update(dataBytes, 0, nread);

        nread = fis.read(dataBytes);/*from   ww w .j  a v a  2 s . com*/

    }
    ;

    byte[] macbytes = mac.doFinal();

    System.out.println("MAC(in hex):: " + ByteUtil.byteArrayToHex(macbytes));

    //3e 17 56 a8 e7 19 4e cc da 87 69 ad 91 a0 b2 1a 83 3d 93 a4

}

From source file:org.gss_project.gss.server.rest.RequestHandler.java

/**
 * Calculates the signature for the specified data String and then
 * compares it against the provided signature. If the signatures match,
 * the method returns true. Otherwise it returns false.
 *
 * @param signature the signature to compare against
 * @param user the current user//w w  w . j  a v  a 2 s .  c om
 * @param data the data to sign
 * @return true if the calculated signature matches the supplied one
 */
protected boolean isSignatureValid(String signature, User user, String data) {
    if (logger.isDebugEnabled())
        logger.debug("server pre-signing data: " + data);
    String serverSignature = null;
    // If the authentication token is not valid, the user must get another one.
    if (user.getAuthToken() == null)
        return false;
    // Get an HMAC-SHA1 key from the authentication token.
    SecretKeySpec signingKey = new SecretKeySpec(user.getAuthToken(), HMAC_SHA1);
    try {
        // Get an HMAC-SHA1 Mac instance and initialize with the signing key.
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        // Compute the HMAC on input data bytes.
        byte[] rawHmac = mac.doFinal(data.getBytes());
        serverSignature = new String(Base64.encodeBase64(rawHmac), "US-ASCII");
    } catch (Exception e) {
        logger.error("Error while creating signature", e);
        return false;
    }

    if (logger.isDebugEnabled())
        logger.debug("Signature: client=" + signature + ", server=" + serverSignature);
    if (!serverSignature.equals(signature))
        return false;

    return true;
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStore.java

@Override
public String getReference(@Nonnull String blobId) {
    checkNotNull(blobId, "BlobId must be specified");
    try {/*from ww w.j av  a 2 s  .  c  om*/
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(getReferenceKey(), ALGORITHM));
        byte[] hash = mac.doFinal(blobId.getBytes("UTF-8"));
        return blobId + ':' + BaseEncoding.base32Hex().encode(hash);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:me.vertretungsplan.parser.WebUntisParser.java

private int authCodeInternal(long time) throws NoSuchAlgorithmException, InvalidKeyException {
    long t = time / 30000;
    byte[] key = new Base32().decode(sharedSecret.toUpperCase().getBytes());
    byte[] data = new byte[8];
    long value = t;
    int i = 8;//from ww w . j a va2s .c om
    while (true) {
        int i2 = i - 1;
        if (i <= 0) {
            break;
        }
        data[i2] = (byte) ((int) value);
        value >>>= 8;
        i = i2;
    }
    SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);
    int offset = hash[19] & 15;
    long truncatedHash = 0;
    for (int i2 = 0; i2 < 4; i2 += 1) {
        truncatedHash = (truncatedHash << 8) | ((long) (hash[offset + i2] & 255));
    }
    return (int) ((truncatedHash & 2147483647L) % 1000000);
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}// ww w  . j a v a  2s .c o  m
 */
@Override
public final byte[] macSha256(byte[] dataToMac, byte[] key) throws McbpCryptoException {
    final String algorithm = "HmacSHA256";
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    try {
        Mac sha256Hmac = Mac.getInstance(algorithm);
        sha256Hmac.init(secretKey);
        return sha256Hmac.doFinal(dataToMac);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:com.streamreduce.util.AWSClient.java

private String calculateS3Signature(String rawUrl, String key, String date) {
    StringBuilder canonical = new StringBuilder();
    try {// ww  w. j a  v a  2 s . c om
        canonical.append("GET").append("\n");
        canonical.append("\n");
        canonical.append("\n");
        canonical.append(date).append("\n");
        canonical.append(rawUrl);
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1"));
        byte[] sign = mac.doFinal(canonical.toString().getBytes("UTF-8"));
        return new String(Base64.encodeBase64(sign));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.streamreduce.util.AWSClient.java

private String calculateSignature(String rawUrl, String key, Map<String, String> params) {
    StringBuilder canonical = new StringBuilder();
    try {/*from   ww  w. ja  v  a 2s  .c  om*/
        canonical.append("GET").append("\n");
        canonical.append(new URL(rawUrl).getHost()).append("\n");
        canonical.append("/").append("\n");
        SortedMap<String, String> sorted = new TreeMap<>(params);
        canonical.append(getQueryString(sorted));
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"));
        byte[] sign = mac.doFinal(canonical.toString().getBytes("UTF-8"));
        return new String(Base64.encodeBase64(sign));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

private boolean verifyRequest(Map<String, Object[]> requestParameters) {
    try {/*from   w w w .  jav a 2s  . com*/
        String apiKey = null;
        String secretKey = null;
        String signature = null;
        String unsignedRequest = null;

        // - build a request string with sorted params, make sure it's all lowercase
        // - sign the request, verify the signature is the same
        List<String> parameterNames = new ArrayList<String>();

        for (Object paramNameObj : requestParameters.keySet()) {
            parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later
        }

        Collections.sort(parameterNames);

        for (String paramName : parameterNames) {
            // parameters come as name/value pairs in the form String/String[]
            String paramValue = ((String[]) requestParameters.get(paramName))[0];

            if ("signature".equalsIgnoreCase(paramName)) {
                signature = paramValue;
            } else {
                if ("apikey".equalsIgnoreCase(paramName)) {
                    apiKey = paramValue;
                }

                if (unsignedRequest == null) {
                    unsignedRequest = paramName + "="
                            + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
                } else {
                    unsignedRequest = unsignedRequest + "&" + paramName + "="
                            + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
                }
            }
        }

        // if api/secret key are passed to the parameters
        if ((signature == null) || (apiKey == null)) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(
                        "expired session, missing signature, or missing apiKey -- ignoring request...sig: "
                                + signature + ", apiKey: " + apiKey);
            }
            return false; // no signature, bad request
        }

        Transaction txn = Transaction.open(Transaction.CLOUD_DB);
        txn.close();
        User user = null;
        // verify there is a user with this api key
        Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey);
        if (userAcctPair == null) {
            s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
            return false;
        }

        user = userAcctPair.first();
        Account account = userAcctPair.second();

        if (!user.getState().equals(Account.State.enabled)
                || !account.getState().equals(Account.State.enabled)) {
            s_logger.debug("disabled or locked user accessing the api, userid = " + user.getId() + "; name = "
                    + user.getUsername() + "; state: " + user.getState() + "; accountState: "
                    + account.getState());
            return false;
        }

        // verify secret key exists
        secretKey = user.getSecretKey();
        if (secretKey == null) {
            s_logger.debug(
                    "User does not have a secret key associated with the account -- ignoring request, username: "
                            + user.getUsername());
            return false;
        }

        unsignedRequest = unsignedRequest.toLowerCase();

        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(unsignedRequest.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        String computedSignature = Base64.encodeBase64URLSafeString(encryptedBytes);
        boolean equalSig = signature.equals(computedSignature);
        if (!equalSig) {
            s_logger.debug("User signature: " + signature + " is not equaled to computed signature: "
                    + computedSignature);
        }

        if (equalSig) {
            requestParameters.put("userid", new Object[] { String.valueOf(user.getId()) });
            requestParameters.put("account", new Object[] { account.getAccountName() });
            requestParameters.put("accountobj", new Object[] { account });
        }
        return equalSig;
    } catch (Exception ex) {
        s_logger.error("unable to verifty request signature", ex);
    }
    return false;
}