Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

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

Prototype

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

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  a va  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:com.cloud.test.stress.StressTestDirectAttach.java

public static String signRequest(String request, String key) {
    try {// w  w w  .  j  av  a2 s  .co 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:com.google.acre.script.HostEnv.java

@JSFunction
public String hmac(String algorithm, String key, String data, boolean to_hex) {
    try {//from w  w  w.ja va 2  s  .  co m
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(signingKey);

        if (to_hex) {
            return new String(Hex.encodeHex(mac.doFinal(data.getBytes())));
        } else {
            return new String(Base64.encodeBase64(mac.doFinal(data.getBytes())));
        }
    } catch (InvalidKeyException e) {
        throw new JSConvertableException("Invalid key: " + key).newJSException(this);
    } catch (NoSuchAlgorithmException e) {
        throw new JSConvertableException("Unable to load algoritm: " + algorithm).newJSException(this);
    }
}

From source file:net.spfbl.core.Core.java

private static long getCodeOTP(byte[] secret, long timeIndex) {
    try {//w  w  w .  java 2s . 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:com.cloud.user.AccountManagerImpl.java

@Override
public UserAccount authenticateUser(String username, String password, Long domainId, String loginIpAddress,
        Map<String, Object[]> requestParameters) {
    UserAccount user = null;/*from  w  ww . j  a  v  a  2s  .  com*/
    if (password != null) {
        user = getUserAccount(username, password, domainId, requestParameters);
    } else {
        String key = _configDao.getValue("security.singlesignon.key");
        if (key == null) {
            // the SSO key is gone, don't authenticate
            return null;
        }

        String singleSignOnTolerance = _configDao.getValue("security.singlesignon.tolerance.millis");
        if (singleSignOnTolerance == null) {
            // the SSO tolerance is gone (how much time before/after system time we'll allow the login request to be
            // valid),
            // don't authenticate
            return null;
        }

        long tolerance = Long.parseLong(singleSignOnTolerance);
        String signature = null;
        long timestamp = 0L;
        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);

        try {
            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 ("timestamp".equalsIgnoreCase(paramName)) {
                        String timestampStr = paramValue;
                        try {
                            // If the timestamp is in a valid range according to our tolerance, verify the request
                            // signature, otherwise return null to indicate authentication failure
                            timestamp = Long.parseLong(timestampStr);
                            long currentTime = System.currentTimeMillis();
                            if (Math.abs(currentTime - timestamp) > tolerance) {
                                if (s_logger.isDebugEnabled()) {
                                    s_logger.debug("Expired timestamp passed in to login, current time = "
                                            + currentTime + ", timestamp = " + timestamp);
                                }
                                return null;
                            }
                        } catch (NumberFormatException nfe) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Invalid timestamp passed in to login: " + timestampStr);
                            }
                            return null;
                        }
                    }

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

            if ((signature == null) || (timestamp == 0L)) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Missing parameters in login request, signature = " + signature
                            + ", timestamp = " + timestamp);
                }
                return null;
            }

            unsignedRequest = unsignedRequest.toLowerCase();

            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            mac.init(keySpec);
            mac.update(unsignedRequest.getBytes());
            byte[] encryptedBytes = mac.doFinal();
            String computedSignature = new String(Base64.encodeBase64(encryptedBytes));
            boolean equalSig = signature.equals(computedSignature);
            if (!equalSig) {
                s_logger.info("User signature: " + signature + " is not equaled to computed signature: "
                        + computedSignature);
            } else {
                user = _userAccountDao.getUserAccount(username, domainId);
            }
        } catch (Exception ex) {
            s_logger.error("Exception authenticating user", ex);
            return null;
        }
    }

    if (user != null) {
        //don't allow to authenticate system user
        if (user.getId() == User.UID_SYSTEM) {
            s_logger.error("Failed to authenticate user: " + username + " in domain " + domainId);
            return null;
        }

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("User: " + username + " in domain " + domainId + " has successfully logged in");
        }
        if (NetUtils.isValidIp(loginIpAddress)) {
            EventUtils.saveEvent(user.getId(), user.getAccountId(), user.getDomainId(),
                    EventTypes.EVENT_USER_LOGIN, "user has logged in from IP Address " + loginIpAddress);
        } else {
            EventUtils.saveEvent(user.getId(), user.getAccountId(), user.getDomainId(),
                    EventTypes.EVENT_USER_LOGIN, "user has logged in. The IP Address cannot be determined");
        }
        return user;
    } else {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("User: " + username + " in domain " + domainId + " has failed to log in");
        }
        return null;
    }
}

From source file:com.emc.esu.test.EsuApiTest.java

@Test
public void testHmac() throws Exception {
    // Compute the signature hash
    String input = "Hello World";
    byte[] secret = Base64.decodeBase64("D7qsp4j16PBHWSiUbc/bt3lbPBY=".getBytes("UTF-8"));
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1");
    mac.init(key);//  w ww .  j a v  a  2s  .c  om
    l4j.debug("Hashing: \n" + input.toString());

    byte[] hashData = mac.doFinal(input.toString().getBytes("ISO-8859-1"));

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

    l4j.debug("Hash: " + hashOut);
}

From source file:com.emc.atmos.api.test.AtmosApiClientTest.java

@Test
public void testHmac() throws Exception {
    // Compute the signature hash
    String input = "Hello World";
    byte[] secret = Base64.decodeBase64("D7qsp4j16PBHWSiUbc/bt3lbPBY=".getBytes("UTF-8"));
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1");
    mac.init(key);/*www .ja  v a2s . co  m*/
    l4j.debug("Hashing: \n" + input);

    byte[] hashData = mac.doFinal(input.getBytes("ISO-8859-1"));

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

    l4j.debug("Hash: " + hashOut);
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static byte[] signMessage(byte[] data, byte[] key, String algorithm)
        throws InvalidKeyException, NoSuchAlgorithmException {
    Mac mac = Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key, algorithm));
    return mac.doFinal(data);
}