Example usage for javax.crypto Mac doFinal

List of usage examples for javax.crypto Mac doFinal

Introduction

In this page you can find the example usage for javax.crypto Mac doFinal.

Prototype

public final byte[] doFinal(byte[] input) throws IllegalStateException 

Source Link

Document

Processes the given array of bytes and finishes the MAC operation.

Usage

From source file:lti.oauth.OAuthMessageSigner.java

/**
 * This method double encodes the parameter keys and values.
 * Thus, it expects the keys and values contained in the 'parameters' SortedMap
 * NOT to be encoded.//  w w  w  .ja  v a2 s.  c o m
 * 
 * @param secret
 * @param algorithm
 * @param method
 * @param url
 * @param parameters
 * @return oauth signature
 * @throws Exception
 */
public String sign(String secret, String algorithm, String method, String url,
        SortedMap<String, String> parameters) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec((secret.concat(OAuthUtil.AMPERSAND)).getBytes(), algorithm);
    Mac mac = Mac.getInstance(secretKeySpec.getAlgorithm());
    mac.init(secretKeySpec);

    StringBuilder signatureBase = new StringBuilder(OAuthUtil.percentEncode(method));
    signatureBase.append(OAuthUtil.AMPERSAND);

    signatureBase.append(OAuthUtil.percentEncode(url));
    signatureBase.append(OAuthUtil.AMPERSAND);

    int count = 0;
    for (String key : parameters.keySet()) {
        count++;
        signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(key)));
        signatureBase.append(URLEncoder.encode(OAuthUtil.EQUAL, OAuthUtil.ENCODING));
        signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(parameters.get(key))));

        if (count < parameters.size()) {
            signatureBase.append(URLEncoder.encode(OAuthUtil.AMPERSAND, OAuthUtil.ENCODING));
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(signatureBase.toString());
    }

    byte[] bytes = mac.doFinal(signatureBase.toString().getBytes());
    byte[] encodedMacBytes = Base64.encodeBase64(bytes);

    return new String(encodedMacBytes);
}

From source file:com.edduarte.protbox.core.registry.PReg.java

public byte[] encrypt(byte[] decryptedData, boolean appendChecksum) throws ProtboxException {
    try {//from w w  w.jav a 2  s . c  o m
        CIPHER.init(Cipher.ENCRYPT_MODE, pair.getPairKey());

        byte[] integrityControlValue = null;
        int checksumLength = 0;
        if (appendChecksum) {
            Mac mac = Mac.getInstance("HmacSHA512");
            mac.init(pair.getIntegrityKey());

            integrityControlValue = mac.doFinal(decryptedData);
            checksumLength = 64;
        }

        byte[] encryptedData = CIPHER.doFinal(decryptedData);

        boolean isCBC = pair.getPairAlgorithm().contains("CBC");
        byte[] iv = CIPHER.getIV();
        int ivLength = isCBC ? 16 : 0;

        byte[] result = new byte[checksumLength + ivLength + encryptedData.length];
        if (appendChecksum) {
            System.arraycopy(integrityControlValue, 0, result, 0, checksumLength);
        }
        if (isCBC) {
            System.arraycopy(iv, 0, result, checksumLength, ivLength);
        }
        System.arraycopy(encryptedData, 0, result, checksumLength + ivLength, encryptedData.length);
        return result;

    } catch (GeneralSecurityException ex) {
        throw new ProtboxException(ex);
    }
}

From source file:com.edduarte.protbox.core.registry.PReg.java

public byte[] decrypt(byte[] encryptedData, boolean hasChecksum) throws ProtboxException {
    try {//ww  w. j ava 2s. co m
        byte[] dataToDecrypt;

        int checksumLength = hasChecksum ? 64 : 0;

        if (pair.getPairAlgorithm().contains("CBC")) {
            byte[] iv = new byte[16];
            System.arraycopy(encryptedData, checksumLength, iv, 0, 16);

            int dataToDecryptLength = encryptedData.length - checksumLength - 16;
            dataToDecrypt = new byte[dataToDecryptLength];
            System.arraycopy(encryptedData, checksumLength + 16, dataToDecrypt, 0, dataToDecryptLength);

            CIPHER.init(Cipher.DECRYPT_MODE, pair.getPairKey(), new IvParameterSpec(iv));

        } else {
            int dataToDecryptLength = encryptedData.length - checksumLength;
            dataToDecrypt = new byte[dataToDecryptLength];
            System.arraycopy(encryptedData, checksumLength, dataToDecrypt, 0, dataToDecryptLength);

            CIPHER.init(Cipher.DECRYPT_MODE, pair.getPairKey());
        }

        byte[] result = CIPHER.doFinal(dataToDecrypt);
        boolean isValid = true;

        if (hasChecksum) {
            byte[] fileCheckSum = new byte[checksumLength];
            System.arraycopy(encryptedData, 0, fileCheckSum, 0, checksumLength);

            Mac mac = Mac.getInstance("HmacSHA512");
            mac.init(pair.getIntegrityKey());
            byte[] integrityControlValue = mac.doFinal(result);

            isValid = Arrays.equals(fileCheckSum, integrityControlValue);
        }

        if (isValid) {
            return result;

        } else {
            throw new ProtboxException("Protected file contains invalid checksum.");
        }

    } catch (GeneralSecurityException ex) {
        throw new ProtboxException(ex);
    }
}

From source file:com.mastfrog.acteur.twitter.TwitterSign.java

String generateSignature(String data, AuthorizationResponse token)
        throws NoSuchAlgorithmException, InvalidKeyException {
    byte[] byteHMAC = null;
    Mac mac = Mac.getInstance(ALGORITHM);
    SecretKeySpec spec;/*from www .  j  a v a2 s.  c om*/
    if (token == null) {
        String signature = HttpParameter.encode(twitter_consumer_secret) + "&";
        spec = new SecretKeySpec(signature.getBytes(), ALGORITHM);
    } else {
        String signature = HttpParameter.encode(twitter_consumer_secret) + "&"
                + HttpParameter.encode(token.accessTokenSecret);
        spec = new SecretKeySpec(signature.getBytes(), ALGORITHM);
    }
    mac.init(spec);
    byteHMAC = mac.doFinal(data.getBytes());
    String sig = BASE64Encoder.encode(byteHMAC);
    return sig;
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java

@Test
public void verify_hmac_256_signature() throws Exception {
    String key = "key";
    String data = "data";
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKey);/*from   ww  w. ja  v  a  2  s  .co m*/
    byte[] hmacData = mac.doFinal(data.getBytes("UTF-8"));
    assertThat(new String(Base64.encodeBase64URLSafe(hmacData)),
            equalTo(xoAuthAuthenticationManager.hmacSignAndEncode(data, key)));
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

private @Nonnull String sign(@Nonnull ProviderContext ctx, @Nonnull String stringToSign)
        throws InternalException {
    try {/*from ww  w . j  av a  2  s . com*/
        Mac mac = Mac.getInstance("HmacSHA1");

        mac.init(new SecretKeySpec(Base64.decodeBase64(new String(ctx.getAccessPrivate(), "utf-8")),
                "HmacSHA1"));
        return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("UTF-8"))), "utf-8");
    } catch (NoSuchAlgorithmException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (IllegalStateException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
}

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 .  j  ava 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:net.spfbl.core.Core.java

private static long getCodeOTP(byte[] secret, long timeIndex) {
    try {/*from  w w  w  . j a v a 2  s .  c o m*/
        SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1");
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(timeIndex);
        byte[] timeBytes = buffer.array();
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signKey);
        byte[] hash = mac.doFinal(timeBytes);
        int offset = hash[19] & 0xf;
        long truncatedHash = hash[offset] & 0x7f;
        for (int i = 1; i < 4; i++) {
            truncatedHash <<= 8;
            truncatedHash |= hash[offset + i] & 0xff;
        }
        return (truncatedHash %= 1000000);
    } catch (Exception ex) {
        return 0;
    }
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

private String generateToken(String attachLocation) {
    if (StringUtils.isEmpty(attachment_key))
        return "";

    SecretKeySpec keySpec = new SecretKeySpec(attachment_key.getBytes(), "HmacMD5");
    Mac mac;
    try {//from ww  w .  j a  v a2s .co m
        mac = Mac.getInstance("HmacMD5");
        mac.init(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    String timestamp = "" + (getSystemTime() + serverTimeDelta);
    byte[] raw = mac.doFinal((timestamp + attachLocation).getBytes());

    return new String(Hex.encodeHex(raw)) + ":" + timestamp;
}

From source file:com.emc.esu.api.rest.AbstractEsuRestApi.java

public String sign(byte[] input)
        throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1");
    mac.init(key);/*ww  w  .j a v a2 s .  com*/

    byte[] hashData = mac.doFinal(input);

    // Encode the hash in Base64.
    return new String(Base64.encodeBase64(hashData), "UTF-8");
}