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.hardisonbrewing.s3j.FileSyncer.java

private byte[] hmacSHA1(String key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {

    SecretKey secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKeySpec);//from  w ww .j  a  va  2 s  .c om
    mac.update(data);
    return mac.doFinal();
}

From source file:be.fedict.eid.idp.webapp.ProtocolExitServlet.java

/**
 * Optionally encrypt the user ID//  w w  w.j a  v  a2 s . c  o  m
 * 
 * @param userId
 *            user ID to encrypt ( or not )
 * @param rp
 *            rp, can be null
 * @return (encrypted) user ID
 */
private String getUniqueId(String userId, RPEntity rp) {

    String uniqueId = userId;

    byte[] hmacSecret = getIdentifierSecret(rp);

    if (null != hmacSecret) {

        Mac mac;
        try {
            mac = CryptoUtil.getMac(hmacSecret);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("Invalid key", e);
        }
        mac.update(uniqueId.getBytes());
        byte[] resultHMac = mac.doFinal();
        uniqueId = new String(Hex.encodeHex(resultHMac)).toUpperCase();
    }
    return uniqueId;
}

From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentials.java

private String computeMacSha(String canonicalizedString) {
    Mac mac;
    try {/*w ww.j  a  v  a2 s  .  c  o  m*/
        if (getKey() == null) {
            throw new StorageClientException(StorageErrorCode.AccountNotFound,
                    "The Windows Azure storage account credentials contains invalid values.",
                    HttpStatusConstant.DEFAULT_STATUS, null, null);
        }
        mac = Mac.getInstance(HMACSHA256);
        mac.init(new SecretKeySpec(getKey(), mac.getAlgorithm()));
        byte[] dataToMAC = canonicalizedString.getBytes(UTF8_CHARSET);
        mac.update(dataToMAC);
        byte[] result = mac.doFinal();
        return Base64.encode(result);
    } catch (NoSuchAlgorithmException e) {
        Logger.error("NoSuchAlgorithmException", e);
    } catch (InvalidKeyException e) {
        Logger.error("InvalidKeyException", e);
    } catch (UnsupportedEncodingException e) {
        Logger.error("UnsupportedEncodingException", e);
    }
    return null;
}

From source file:org.sakaiproject.nakamura.auth.trusted.TokenStore.java

/**
 * @throws NoSuchAlgorithmException//from  www . j  a v  a  2s .c  o  m
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws IllegalStateException
 *
 */
public TokenStore() throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {
    random = SecureRandom.getInstance(SHA1PRNG);
    // warm up the crypto API
    Mac m = Mac.getInstance(HMAC_SHA1);
    byte[] b = new byte[20];
    random.nextBytes(b);
    SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1);
    m.init(secretKey);
    m.update(UTF_8.getBytes(UTF_8));
    m.doFinal();
    this.tokenFile = new File(DEFAULT_TOKEN_FILE);
    tmpTokenFile = new File(DEFAULT_TOKEN_FILE + ".tmp");

}

From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java

public String getTransferUserId(HttpServletRequest request) {
    // only ever get a user ID in this way on a non trusted safe host.
    if (disableProtectionForDevMode) {
        LOGGER.warn("XSS Protection is disabled [getTransferUserId]");
        return null;
    }// ww w.  ja  v a  2 s .  c om
    // the host must not be safe to decode the user transfer UserID, and the method must be a GET or HEAD
    String method = request.getMethod();
    if (!isSafeHost(request) && ("GET".equals(method) || "HEAD".equals(method))) {
        String hmac = request.getParameter(HMAC_PARAM);
        if (hmac != null) {
            try {
                hmac = new String(Base64.decodeBase64(hmac.getBytes("UTF-8")), "UTF-8");
                String[] parts = StringUtils.split(hmac, ';');
                String requestUrl = request.getRequestURL().append("?").append(request.getQueryString())
                        .toString();
                LOGGER.debug("Checking requestUrl [{}", requestUrl);
                int i = requestUrl.indexOf("&" + HMAC_PARAM);
                if (i < 0) {
                    i = requestUrl.indexOf("?" + HMAC_PARAM);
                }
                String finalUrl = requestUrl.substring(0, i);
                String requestHmac = parts[0];
                String requestUserId = parts[1];
                String requestTs = parts[2];
                String message = createMessage(finalUrl, requestUserId, requestTs);
                long requestTsL = Long.parseLong(requestTs);
                if (Math.abs(System.currentTimeMillis() - requestTsL) < 60000L) {
                    int keyIndex = (int) (requestTsL - ((requestTsL / 10) * 10));
                    Mac m = Mac.getInstance(HMAC_SHA512);
                    m.init(transferKeys[keyIndex]);
                    m.update(message.getBytes("UTF-8"));
                    String testHmac = Base64.encodeBase64URLSafeString(m.doFinal());
                    if (testHmac.equals(requestHmac)) {
                        LOGGER.debug("Successfully extracted requestUserId {} from HMAC", requestUserId);
                        return requestUserId;
                    } else {
                        LOGGER.debug("Message was [{}] ", message);
                        LOGGER.debug("Key was [{}] [{}] ", keyIndex, transferKeys[keyIndex]);
                        LOGGER.debug("Hmac did not validate testHmac was [{}], requestHmac [{}] ", testHmac,
                                requestHmac);
                    }
                } else {
                    LOGGER.debug("Hmac has expired, older than 60s, hmac message was {} ", message);
                }
            } catch (Exception e) {
                LOGGER.warn(e.getMessage());
                LOGGER.debug(e.getMessage(), e);
            }
        }
    } else {
        LOGGER.debug("Request is to a safe host, wont look for a transfer of trust to this host. {} ",
                request.getRequestURL().toString());
    }
    return null;
}

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

private boolean verifyRequest(Map<String, Object[]> requestParameters) {
    try {/* ww w .jav  a  2  s  . c  om*/
        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;
}

From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java

/**
 * @param request/*  w w w .  j  a v  a  2 s .  c  om*/
 * @param urlPath
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws UnsupportedEncodingException
 */
private String getTransferUrl(HttpServletRequest request, String urlPath) {
    String trustedHostHeader = buildTrustedHostHeader(request);
    if (trustedHostHeader == null || !applicationContentRedirects.containsKey(trustedHostHeader)) {
        LOGGER.warn("No Content Host found for {} ", request.getRequestURL());
        throw new IllegalArgumentException("No Content Host foudn for request, cant transfer ");
    }
    String redirectUrl = applicationContentRedirects.get(trustedHostHeader) + urlPath;
    // only transfer authN from a trusted safe host
    if (isSafeHost(request)) {
        String userId = request.getRemoteUser();
        if (userId != null && !User.ANON_USER.equals(userId)) {
            try {
                long ts = System.currentTimeMillis();
                int keyIndex = (int) (ts - ((ts / 10) * 10));
                Mac m = Mac.getInstance(HMAC_SHA512);
                m.init(transferKeys[keyIndex]);

                String message = createMessage(redirectUrl, userId, String.valueOf(ts));

                m.update(message.getBytes("UTF-8"));
                String hmac = Base64.encodeBase64URLSafeString(m.doFinal());
                hmac = Base64.encodeBase64URLSafeString((hmac + ";" + userId + ";" + ts).getBytes("UTF-8"));
                String spacer = "?";
                if (redirectUrl.indexOf('?') > 0) {
                    spacer = "&";
                }
                redirectUrl = redirectUrl + spacer + HMAC_PARAM + "=" + hmac;
                LOGGER.debug("Message was [{}] ", message);
                LOGGER.debug("Key was [{}] [{}] ", keyIndex, transferKeys[keyIndex]);
                LOGGER.debug("Transfer URL created as [{}] ", redirectUrl);
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
    return redirectUrl;
}

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

final void verifyMac(Uri path, String grantMode, String requested) throws FileNotFoundException {
    if (Process.myUid() == Binder.getCallingUid()) {
        return;//from   w  w w  .  ja  v a 2s  . c  om
    }

    final int requestedMode = ParcelFileDescriptor.parseMode(requested);

    final String cookie = path.getQueryParameter(URI_ARG_COOKIE);
    final String expiry = path.getQueryParameter(URI_ARG_EXPIRY);

    if (TextUtils.isEmpty(cookie) || TextUtils.isEmpty(expiry)) {
        throw new FileNotFoundException("Invalid uri: MAC and expiry date are missing");
    }

    final long l;
    try {
        l = Long.parseLong(expiry);
    } catch (NumberFormatException nfe) {
        throw new FileNotFoundException("Invalid uri: unable to parse expiry date");
    }

    final Key key = getSalt(getContext());
    if (key == null) {
        throw new FileNotFoundException("Unable to verify hash: failed to produce key");
    }

    final int modeInt = ParcelFileDescriptor.parseMode(grantMode);

    if ((requestedMode & modeInt) != requestedMode) {
        throw new FileNotFoundException("Requested mode " + requested + " but limited to " + grantMode);
    }

    final byte[] encoded;
    final Mac hash;
    try {
        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(path.getPath().getBytes());

        final String sample = Base64.encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING);

        if (!cookie.equals(sample)) {
            throw new FileNotFoundException("Expired uri");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new FileNotFoundException("Unable to verify hash: missing HmacSHA1");
    } catch (InvalidKeyException e) {
        throw new FileNotFoundException("Unable to verify hash: corrupted key?!");
    }
}

From source file:org.androdyne.StacktraceUploader.java

/**
 * Given the NameValuePairs forming a stacktrace submission request, creates a
 * signature over the parameters that the API should recognize.
 **//* w w  w. j  a v a2 s. c om*/
private String createSignature(List<NameValuePair> params) {
    // First, sort the parameter keys. That'll help later.
    List<String> sortedKeys = new LinkedList<String>();
    for (NameValuePair pair : params) {
        sortedKeys.add(pair.getName());
    }
    Collections.sort(sortedKeys, String.CASE_INSENSITIVE_ORDER);

    // Create signature.
    Mac hmac = null;
    try {
        hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(mAPISecret.getBytes(), "HmacSHA1"));
    } catch (NoSuchAlgorithmException ex) {
        android.util.Log.e(LTAG, "No HmacSHA1 available on this phone.");
        return null;
    } catch (InvalidKeyException ex) {
        android.util.Log.e(LTAG, "Invalid secret; shouldn't be possible.");
        return null;
    }

    final int size = sortedKeys.size();
    for (int i = 0; i < size; ++i) {
        String key = sortedKeys.get(i);

        for (NameValuePair pair : params) {
            if (!key.equals(pair.getName())) {
                continue;
            }

            // This pair is next!
            try {
                hmac.update(String.format("%s=%s", key, URLEncoder.encode(pair.getValue(), "utf8")).getBytes());
            } catch (java.io.UnsupportedEncodingException ex) {
                android.util.Log.e(LTAG, "URLEncoder reports 'utf8' is an unsupported encoding...");
                return null;
            }
            if (i < size - 1) {
                hmac.update("&".getBytes());
            }
        }
    }

    String signature = new BigInteger(1, hmac.doFinal()).toString(16);
    // android.util.Log.d(LTAG, "signature: " + signature);
    return signature;
}

From source file:example.DecrypterException.java

/**
 * Performs the decryption algorithm.//from   www .j a  va 2s . c om
 *
 * 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);
    }
}