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.sharextras.webscripts.connector.HttpOAuthConnector.java

private String generateSignature(Map<String, String> authParams, Map<String, String> extraParams,
        String httpMethod, String url) {
    Map<String, String> sigParams = new HashMap<String, String>(authParams);
    if (extraParams != null)
        sigParams.putAll(extraParams);//from ww  w  . j a v  a  2s .  c  o  m

    String sigMethod = sigParams.get(OAUTH_SIGNATURE_METHOD);

    if (sigMethod.equals(SIGNATURE_METHOD_PLAINTEXT)) {
        if (logger.isDebugEnabled())
            logger.debug("Generating PLAINTEXT signature");
        String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET);
        StringBuffer signatureBuffer = new StringBuffer(getConsumerSecret()).append("&");
        signatureBuffer.append(tokenSecret != null ? tokenSecret : "");
        return signatureBuffer.toString();
    } else if (sigMethod.equals(SIGNATURE_METHOD_HMACSHA1)) {
        if (logger.isDebugEnabled())
            logger.debug("Generating HMAC-SHA1 signature");

        StringBuffer baseStrBuffer = new StringBuffer();

        baseStrBuffer.append(httpMethod).append("&");
        baseStrBuffer.append(encodeParameter(url));
        baseStrBuffer.append("&");

        // Add all request params to the list, combine request and auth params in a single map
        // as per http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
        // TODO Support multiple parameters with same name

        // Sort keys by param name
        // TODO Sort *after* encoding
        List<String> keys = new ArrayList<String>(sigParams.keySet());
        Collections.sort(keys);
        int i = 0;
        for (String key : keys) {
            if (!key.equals(OAUTH_REALM) && !key.equals(OAUTH_SIGNATURE) && !key.equals(OAUTH_TOKEN_SECRET)) {
                if (i > 0)
                    baseStrBuffer.append(encodeParameter("&"));
                baseStrBuffer.append(
                        encodeParameter(encodeParameter(key) + "=" + encodeParameter(sigParams.get(key))));
                i++;
            }
        }

        // Final base string
        String baseString = baseStrBuffer.toString();

        // Key to use for signing
        String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET);
        String key = encodeParameter(getConsumerSecret()) + "&"
                + encodeParameter(tokenSecret != null ? tokenSecret : "");

        if (logger.isDebugEnabled())
            logger.debug("Generating signature with key '" + key + "', base string '" + baseString + "'");

        try {
            SecretKey keyStr = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac m = Mac.getInstance("HmacSHA1");
            m.init(keyStr);
            m.update(baseString.getBytes());
            byte[] mac = m.doFinal();
            return new String(Base64.encodeBytes(mac)).trim();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static String signRequest(String request, String key) {
    try {/*from w  w w . j  ava  2 s  .c o m*/
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        return Base64.encodeBase64String(encryptedBytes);
    } catch (Exception ex) {
        s_logger.error("unable to sign request", ex);
    }
    return null;
}

From source file:org.opencredo.cloud.storage.azure.rest.internal.RequestAuthorizationInterceptor.java

/**
 * @param signatureString/*from   ww w . java2 s . co m*/
 * @return
 */
private String createSignature(String signatureString) throws RequestAuthorizationException {
    String encoding = "UTF-8";
    String encryptionAlgorithm = "HmacSHA256";
    try {
        Mac mac = Mac.getInstance(encryptionAlgorithm);
        mac.init(new SecretKeySpec(Base64.decodeBase64(credentials.getSecretKey()), mac.getAlgorithm()));
        byte[] dataToMAC = signatureString.getBytes(encoding);
        mac.update(dataToMAC);
        byte[] result = mac.doFinal();
        return new String(Base64.encodeBase64(result));
    } catch (InvalidKeyException e) {
        throw new RequestAuthorizationException(
                "Provided secret key is inappropriate to encrypt signature-string.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RequestAuthorizationException(
                "No algorithm [" + encryptionAlgorithm + "] to encrypt signature-string.", e);
    } catch (UnsupportedEncodingException e) {
        throw new RequestAuthorizationException(
                "Unable to convert signature-string to encoding - '" + encoding + "'.", e);
    } catch (IllegalStateException e) {
        throw new RequestAuthorizationException("Illegal signature-string encryption state.", e);
    }
}

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

private String encode(final long expires, final String userId, final int token, final SecretKey key)
        throws IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {/*from  w w w. j  a  va2 s.  c om*/

    String cookiePayload = String.valueOf(token) + String.valueOf(expires) + "@" + userId;
    Mac m = Mac.getInstance(HMAC_SHA1);
    m.init(key);
    m.update(cookiePayload.getBytes(UTF_8));
    String cookieValue = byteToHex(m.doFinal());
    return cookieValue + "@" + cookiePayload;
}

From source file:org.callimachusproject.behaviours.AuthenticationManagerSupport.java

private String sig(String text) throws OpenRDFException, IOException, GeneralSecurityException {
    String secret = this.getRealm().getOriginSecret();
    SecretKey key = new SecretKeySpec(readBytes(secret), "HmacSHA256");
    Mac m = Mac.getInstance("HmacSHA256");
    m.init(key);//  w  ww . j a  v a2 s  .c o  m
    m.update(text.getBytes("UTF-8"));
    return Base64.encodeBase64String(m.doFinal());
}

From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.SignatureGenerator.java

public String getSignature(String secretKey) {
    Mac mac;
    try {//from w  w  w.  j  a  v a2  s  .  c om
        mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(secretKey.getBytes(), ALGORITHM));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }
    mac.update(method.getBytes());
    mac.update((byte) '\n');
    mac.update(host.getBytes());
    mac.update((byte) '\n');
    mac.update(path.getBytes());
    mac.update((byte) '\n');

    boolean addAmpersand = false;
    for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
        byte[] nameBytes = encodeString(entry.getKey());
        List<String> values = entry.getValue();
        Collections.sort(values);
        for (String value : values) {
            if (addAmpersand) {
                mac.update((byte) '&');
            } else {
                addAmpersand = true;
            }
            byte[] valueBytes = encodeString(value);
            mac.update(nameBytes);
            mac.update((byte) '=');
            mac.update(valueBytes);
        }
    }

    byte[] digest = mac.doFinal();
    return new String(Base64.encodeBase64(digest));
}

From source file:mitm.application.djigzo.james.matchers.VerifyHMACHeader.java

private String calculateHMAC(String value, Mail mail) throws MessagingException, MissingSecretException {
    try {// w  w  w.  j  a v  a2s  .c  o  m
        Mac mac = securityFactory.createMAC(ALGORITHM);

        byte[] secret = getSecret(mail);

        if (secret == null) {
            throw new MissingSecretException();
        }

        SecretKeySpec keySpec = new SecretKeySpec(secret, "raw");

        mac.init(keySpec);

        mac.update(MiscStringUtils.toAsciiBytes(value));

        return HexUtils.hexEncode(mac.doFinal());
    } catch (NoSuchAlgorithmException e) {
        throw new MessagingException("Error creating HMAC.", e);
    } catch (NoSuchProviderException e) {
        throw new MessagingException("Error creating HMAC.", e);
    } catch (InvalidKeyException e) {
        throw new MessagingException("Error creating HMAC.", e);
    }
}

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

/**
 * @throws NoSuchAlgorithmException/*from  w w  w .j  av a2 s .c  o 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:org.picketbox.json.enc.JSONWebEncryption.java

private byte[] performMac(byte[] key, byte[] data) throws ProcessingException {
    Mac mac = null;
    try {//from   w  w w .  java2s  .c  om
        mac = Mac.getInstance(jsonWebEncryptionHeader.getMessageAuthenticationCodeAlgo());

        mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
        mac.update(data);
        return mac.doFinal();
    } catch (Exception e) {
        throw PicketBoxJSONMessages.MESSAGES.processingException(e);
    }
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected String createHmac(SharedPreferences pref, String content, boolean stripEquals)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    String secret = getString(pref, Secret);
    SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
    Mac hmac = Mac.getInstance(HMAC);
    hmac.init(key);//from   w  ww  . ja va 2  s  .c o  m
    hmac.update(content.getBytes(UTF8));
    byte[] bytes = hmac.doFinal();
    String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim();
    if (stripEquals)
        derived = derived.replaceAll("=", "");

    return derived;
}