List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:org.dasein.cloud.aws.AWSCloud.java
private String sign(byte[] key, String authString, String algorithm) throws InternalException { try {/*w w w. jav a 2 s .co m*/ Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return new String(Base64.encodeBase64(mac.doFinal(authString.getBytes("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:org.gaul.s3proxy.S3ProxyHandler.java
/** * Create Amazon V2 signature. Reference: * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html */// w ww .j a v a2s . c o m private static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) { // sort Amazon headers SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create(); for (String headerName : Collections.list(request.getHeaderNames())) { Collection<String> headerValues = Collections.list(request.getHeaders(headerName)); headerName = headerName.toLowerCase(); if (!headerName.startsWith("x-amz-")) { continue; } if (headerValues.isEmpty()) { canonicalizedHeaders.put(headerName, ""); } for (String headerValue : headerValues) { canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue)); } } // build string to sign StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n') .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n') .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n'); String expires = request.getParameter("Expires"); if (expires != null) { builder.append(expires); } else if (!canonicalizedHeaders.containsKey("x-amz-date")) { builder.append(request.getHeader(HttpHeaders.DATE)); } builder.append('\n'); for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) { builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n'); } builder.append(uri); char separator = '?'; List<String> subresources = Collections.list(request.getParameterNames()); Collections.sort(subresources); for (String subresource : subresources) { if (SIGNED_SUBRESOURCES.contains(subresource)) { builder.append(separator).append(subresource); String value = request.getParameter(subresource); if (!"".equals(value)) { builder.append('=').append(value); } separator = '&'; } } String stringToSign = builder.toString(); logger.trace("stringToSign: {}", stringToSign); // sign string Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))); }
From source file:de.andreas_rueckert.trade.site.mtgox.client.MtGoxClient.java
/** * Create authentication entries for a HTTP post header. * * @param postData The data to post via HTTP. * @param userAccount The account of the user on the exchange. Null, if the default account should be used. * * @return The header entries as a map or null if an error occured. *///from w w w.ja va 2 s. co m Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) { HashMap<String, String> result = new HashMap<String, String>(); Mac mac; String accountKey = null; String accountSecret = null; // Try to get user account and secret. if (userAccount != null) { accountKey = userAccount.getAPIkey(); accountSecret = userAccount.getSecret(); } else { // Use the default account from the API implementation. accountKey = _key; accountSecret = _secret; } // Check, if key and secret are available for the request. if (accountKey == null) { throw new MissingAccountDataException("Key not available for authenticated request to MtGox"); } if (accountSecret == null) { throw new MissingAccountDataException("Secret not available for authenticated request to MtGox"); } result.put("Rest-Key", accountKey); // Create a new secret key SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512"); // Create a new mac try { mac = Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException nsae) { System.err.println("No such algorithm exception: " + nsae.toString()); return null; } // Init mac with key. try { mac.init(key); } catch (InvalidKeyException ike) { System.err.println("Invalid key exception: " + ike.toString()); return null; } // Encode the post data by the secret and encode the result as base64. try { result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8")))); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } return result; }
From source file:de.andreas_rueckert.trade.site.anx.client.ANXClient.java
/** * Create authentication entries for a HTTP post header. * * @param postData The data to post via HTTP. * @param userAccount The account of the user on the exchange. Null, if the default account should be used. * * @return The header entries as a map or null if an error occured. *//*from www . j a va 2 s .c om*/ Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) { HashMap<String, String> result = new HashMap<String, String>(); Mac mac; String accountKey = null; String accountSecret = null; // Try to get user account and secret. if (userAccount != null) { accountKey = userAccount.getAPIkey(); accountSecret = userAccount.getSecret(); } else { // Throw an error. throw new MissingAccountDataException("No user account given for " + _name + " request"); } // Check, if key and secret are available for the request. if (accountKey == null) { throw new MissingAccountDataException("Key not available for authenticated request to " + _name); } if (accountSecret == null) { throw new MissingAccountDataException("Secret not available for authenticated request to " + _name); } result.put("Rest-Key", accountKey); // Create a new secret key SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512"); // Create a new mac try { mac = Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException nsae) { System.err.println("No such algorithm exception: " + nsae.toString()); return null; } // Init mac with key. try { mac.init(key); } catch (InvalidKeyException ike) { System.err.println("Invalid key exception: " + ike.toString()); return null; } // Encode the post data by the secret and encode the result as base64. try { result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8")))); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } return result; }
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); 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:org.gaul.s3proxy.S3ProxyHandler.java
private void handlePostBlob(HttpServletRequest request, HttpServletResponse response, InputStream is, BlobStore blobStore, String containerName) throws IOException, S3Exception { String boundaryHeader = request.getHeader(HttpHeaders.CONTENT_TYPE); if (boundaryHeader == null || !boundaryHeader.startsWith("multipart/form-data; boundary=")) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return;//from ww w. ja va 2s. co m } String boundary = boundaryHeader.substring(boundaryHeader.indexOf('=') + 1); String blobName = null; String contentType = null; String identity = null; // TODO: handle policy byte[] policy = null; String signature = null; byte[] payload = null; MultipartStream multipartStream = new MultipartStream(is, boundary.getBytes(StandardCharsets.UTF_8), 4096, null); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { multipartStream.readBodyData(baos); if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"acl\"")) { // TODO: acl } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"AWSAccessKeyId\"")) { identity = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"Content-Type\"")) { contentType = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"file\"")) { // TODO: buffers entire payload payload = baos.toByteArray(); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"key\"")) { blobName = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"policy\"")) { policy = baos.toByteArray(); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"signature\"")) { signature = new String(baos.toByteArray()); } } nextPart = multipartStream.readBoundary(); } if (identity == null || signature == null || blobName == null || policy == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(identity, null, null); if (provider == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } String credential = provider.getKey(); Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } String expectedSignature = BaseEncoding.base64().encode(mac.doFinal(policy)); if (!signature.equals(expectedSignature)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } BlobBuilder.PayloadBlobBuilder builder = blobStore.blobBuilder(blobName).payload(payload); if (contentType != null) { builder.contentType(contentType); } Blob blob = builder.build(); blobStore.putBlob(containerName, blob); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
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. j a v a2s . c om 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.// w ww . j a v a2 s. 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 w w . ja v a2s . c o 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; }