List of usage examples for javax.crypto Mac update
public final void update(ByteBuffer input)
From source file:com.cloud.api.ApiServer.java
public boolean verifyRequest(Map<String, Object[]> requestParameters, Long userId) throws ServerApiException { try {/*from w w w . ja v a2 s . c om*/ String apiKey = null; String secretKey = null; String signature = null; String unsignedRequest = null; String[] command = (String[]) requestParameters.get("command"); if (command == null) { s_logger.info("missing command, ignoring request..."); return false; } String commandName = command[0]; // if userId not null, that mean that user is logged in if (userId != null) { Long accountId = ApiDBUtils.findUserById(userId).getAccountId(); Account userAccount = _accountMgr.getAccount(accountId); short accountType = userAccount.getType(); if (!isCommandAvailable(accountType, commandName)) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); } return true; } else { // check against every available command to see if the command exists or not if (!isCommandAvailable(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); } } // - 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); String signatureVersion = null; String expires = null; 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; } else if ("signatureversion".equalsIgnoreCase(paramName)) { signatureVersion = paramValue; } else if ("expires".equalsIgnoreCase(paramName)) { expires = 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.info( "expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); } return false; // no signature, bad request } Date expiresTS = null; if ("3".equals(signatureVersion)) { // New signature authentication. Check for expire parameter and its validity if (expires == null) { s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); return false; } synchronized (_dateFormat) { try { expiresTS = _dateFormat.parse(expires); } catch (ParseException pe) { s_logger.info("Incorrect date format for Expires parameter", pe); return false; } } Date now = new Date(System.currentTimeMillis()); if (expiresTS.before(now)) { s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey); return false; } } 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.info("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } user = userAcctPair.first(); Account account = userAcctPair.second(); if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) { s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState()); return false; } UserContext.updateContext(user.getId(), account, null); if (!isCommandAvailable(account.getType(), commandName)) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist"); } // verify secret key exists secretKey = user.getSecretKey(); if (secretKey == null) { s_logger.info( "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.encodeBase64String(encryptedBytes); boolean equalSig = signature.equals(computedSignature); if (!equalSig) { s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature); } return equalSig; } catch (Exception ex) { if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) { throw (ServerApiException) ex; } s_logger.error("unable to verifty request signature", ex); } return false; }
From source file:com.cloud.test.stress.TestClientWithAPI.java
public static String signRequest(String request, String key) { try {//from w ww . ja v a 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 org.apache.commons.codec.binary.Base64.encodeBase64String(encryptedBytes); } catch (Exception ex) { s_logger.error("unable to sign request", ex); } return null; }
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 w w.java2s . co m 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.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java
/** * Creates request for device SRP verification. * * @param challenge REQUIRED: {@link RespondToAuthChallengeResult} contains * next challenge.//from w w w . j ava2s.c o m * @param deviceSecret REQUIRED: Device secret verifier. * @param authenticationHelper REQUIRED: Internal helper class for SRP * calculations. * @param deviceGroupKey the device group key * @return {@link RespondToAuthChallengeRequest}. */ public RespondToAuthChallengeRequest deviceSrpAuthRequest(RespondToAuthChallengeResult challenge, String deviceSecret, String deviceGroupKey, AuthenticationHelper authenticationHelper) { this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME); final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16); if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) { throw new CognitoInternalErrorException("SRP error, B cannot be zero"); } final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16); final byte[] key = authenticationHelper.getPasswordAuthenticationKey(deviceKey, deviceSecret, srpB, salt); final Date timestamp = new Date(); byte[] hmac; String dateString; try { final Mac mac = Mac.getInstance("HmacSHA256"); final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256"); mac.init(keySpec); mac.update(deviceGroupKey.getBytes(StringUtils.UTF8)); mac.update(deviceKey.getBytes(StringUtils.UTF8)); final byte[] secretBlock = Base64.decode( challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK)); mac.update(secretBlock); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); dateString = simpleDateFormat.format(timestamp); final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8); hmac = mac.doFinal(dateBytes); } catch (final Exception e) { throw new CognitoInternalErrorException("SRP error", e); } secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret); final Map<String, String> srpAuthResponses = new HashMap<String, String>(); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK, challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK)); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE, new String(Base64.encode(hmac), StringUtils.UTF8)); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash); final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest(); authChallengeRequest.setChallengeName(challenge.getChallengeName()); authChallengeRequest.setClientId(clientId); authChallengeRequest.setSession(challenge.getSession()); authChallengeRequest.setChallengeResponses(srpAuthResponses); return authChallengeRequest; }
From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java
/** * Creates response for the second step of the SRP authentication. * * @param challenge REQUIRED: {@link InitiateAuthResult} contains next * challenge./*from w ww . j av a 2 s . co m*/ * @param authenticationDetails REQUIRED: {@link AuthenticationDetails} user * authentication details. * @param authenticationHelper REQUIRED: Internal helper class for SRP * calculations. * @return {@link RespondToAuthChallengeRequest}. */ private RespondToAuthChallengeRequest userSrpAuthRequest(InitiateAuthResult challenge, AuthenticationDetails authenticationDetails, AuthenticationHelper authenticationHelper) { final String userIdForSRP = challenge.getChallengeParameters() .get(CognitoServiceConstants.CHLG_PARAM_USER_ID_FOR_SRP); this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME); this.deviceKey = CognitoDeviceHelper.getDeviceKey(usernameInternal, pool.getUserPoolId(), context); secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret); final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16); if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) { throw new CognitoInternalErrorException("SRP error, B cannot be zero"); } final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16); final byte[] key = authenticationHelper.getPasswordAuthenticationKey(userIdForSRP, authenticationDetails.getPassword(), srpB, salt); final Date timestamp = new Date(); byte[] hmac; String dateString; try { final Mac mac = Mac.getInstance("HmacSHA256"); final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256"); mac.init(keySpec); mac.update(pool.getUserPoolId().split("_", 2)[1].getBytes(StringUtils.UTF8)); mac.update(userIdForSRP.getBytes(StringUtils.UTF8)); final byte[] secretBlock = Base64.decode(challenge.getChallengeParameters().get("SECRET_BLOCK")); mac.update(secretBlock); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); dateString = simpleDateFormat.format(timestamp); final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8); hmac = mac.doFinal(dateBytes); } catch (final Exception e) { throw new CognitoInternalErrorException("SRP error", e); } final Map<String, String> srpAuthResponses = new HashMap<String, String>(); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK, challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK)); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE, new String(Base64.encode(hmac), StringUtils.UTF8)); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey); srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash); final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest(); authChallengeRequest.setChallengeName(challenge.getChallengeName()); authChallengeRequest.setClientId(clientId); authChallengeRequest.setSession(challenge.getSession()); authChallengeRequest.setChallengeResponses(srpAuthResponses); return authChallengeRequest; }
From source file:com.cloud.server.ManagementServerImpl.java
private String signRequest(String request, String key) { try {//from www .j a va 2s . c o m s_logger.info("Request: " + request); s_logger.info("Key: " + key); if (key != null && request != null) { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); return new String((Base64.encodeBase64(encryptedBytes))); } } catch (Exception ex) { s_logger.error("unable to sign request", ex); } return null; }