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:net.sf.xfd.provider.PublicProvider.java

final void verifyMac(Uri path, String grantMode, String requested) throws FileNotFoundException {
    if (Process.myUid() == Binder.getCallingUid()) {
        return;//  ww w.j ava2 s.com
    }

    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.instagram4j.DefaultInstagramClient.java

private void setEnforceHeader(HttpRequestBase method) {
    if (!isSignedHeaderEnabled())
        return;/*from   w w  w  .  ja va 2s.c o m*/

    if (clientSecret == null)
        throw new IllegalStateException("Client secret it required to use signed header");

    if (clientIps == null || clientIps.length() == 0)
        throw new IllegalStateException("Client IP(s) required to use signed header");

    try {
        SecretKeySpec signingKey = new SecretKeySpec(getClientSecret().getBytes(), HMAC_SHA256_ALGO);

        Mac mac = Mac.getInstance(HMAC_SHA256_ALGO);
        mac.init(signingKey);

        // Compute the hmac on IP address.
        byte[] rawHmac = mac.doFinal(clientIps.getBytes());

        String digest = Hex.encodeHexString(rawHmac);

        method.setHeader("X-Insta-Forwarded-For", String.format("%s|%s", clientIps, digest));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Unexpected error creating signed header using HMAC-SHA256", e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("Unexpected error creating signed header using HMAC-SHA256", e);
    }
}

From source file:org.dasein.cloud.skeleton.RESTMethod.java

private @Nonnull String getSignature(@Nonnull byte[] accessKey, @Nonnull byte[] privateKey,
        @Nonnull String method, @Nonnull String resource, @Nullable String id, long timestamp)
        throws InternalException {
    // TODO: implement this for real; this is the signature code for the enStratus API (sorta)
    try {/*w ww. j  a v  a  2  s  .c o  m*/
        String stringToSign = (new String(accessKey, "utf-8")) + ":" + method;

        if (resource.startsWith("/")) {
            stringToSign = stringToSign + resource;
        } else {
            stringToSign = stringToSign + "/" + resource;
        }
        if (id != null) {
            if (id.startsWith("/")) {
                stringToSign = stringToSign + id;
            } else {
                stringToSign = stringToSign + "/" + id;
            }
        }
        stringToSign = stringToSign + ":" + timestamp + ":Dasein Cloud";

        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(privateKey, "HmacSHA256"));
            return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("utf-8"))));
        } catch (NoSuchAlgorithmException e) {
            throw new InternalException(e);
        } catch (InvalidKeyException e) {
            throw new InternalException(e);
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    }
}

From source file:TimestreamsTests.java

/**
 * Generate an HMAC Based on example://w  w  w . ja v  a 2 s .  c  o  m
 * http://stackoverflow.com/questions/6312544
 * /hmac-sha1-how-to-do-it-properly-in-java
 * 
 * @param value
 *            is a String to hash
 * @param key
 *            is the private key to hash with#
 * @param type
 *            is the Mac format to use such as HmacSHA256
 * @return The hmac
 */
private String hmacString(String value, String key, String type) {
    try {
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, type);

        // Get a Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(type);
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        // Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        fail = e.getLocalizedMessage();
        return null;
    }
}

From source file:com.lili.ylpay.sdk.SecureUtil.java

/**
 * MAC/* w  w  w.  j a  v  a  2s  . c om*/
 * 
 * @param inputByte
 *            ?
 * @param inputkey
 *            
 * @param inputmac
 *            MAC
 * @return 
 * @throws Exception
 */
public boolean checkmac(byte[] inputByte, byte[] inputkey, String inputmac) throws Exception {
    try {
        Mac mac = Mac.getInstance("HmacMD5");
        SecretKey key = new SecretKeySpec(inputkey, "DES");
        mac.init(key);

        byte[] macCode = mac.doFinal(inputByte);
        String strMacCode = this.byte2hex(macCode);

        return strMacCode.equals(inputmac);
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:acp.sdk.SecureUtil.java

/**
 * MAC/*from   ww w .  j  av  a2s  .  c  o m*/
 * 
 * @param inputByte
 *            ?
 * @param inputkey
 *            
 * @return MAC
 * @throws Exception
 */
public String genmac(byte[] inputByte, byte[] inputkey) throws Exception {
    try {
        Mac mac = Mac.getInstance("HmacMD5");
        SecretKey key = new SecretKeySpec(inputkey, "DES");
        mac.init(key);

        byte[] macCode = mac.doFinal(inputByte);
        String strMac = this.byte2hex(macCode);
        return strMac;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    }
}

From source file:acp.sdk.SecureUtil.java

/**
 * MAC//from   w w w .ja  v  a2  s  .c  om
 * 
 * @param inputByte
 *            ?
 * @param inputkey
 *            
 * @param inputmac
 *            MAC
 * @return 
 * @throws Exception
 */
public boolean checkmac(byte[] inputByte, byte[] inputkey, String inputmac) throws Exception {
    try {
        Mac mac = Mac.getInstance("HmacMD5");
        SecretKey key = new SecretKeySpec(inputkey, "DES");
        mac.init(key);

        byte[] macCode = mac.doFinal(inputByte);
        String strMacCode = this.byte2hex(macCode);

        if (strMacCode.equals(inputmac)) {
            return true;
        } else {
            return false;
        }
    } catch (Exception ex) {
        throw ex;
    }
}

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.co  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 {/*from  w w  w  .  j  ava  2 s  . 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:org.dasein.cloud.atmos.AtmosMethod.java

private @Nonnull String sign(@Nonnull ProviderContext ctx, @Nonnull String stringToSign)
        throws InternalException {
    try {/*from  w w w  .jav  a 2 s.  c o  m*/
        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);
    }
}