List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:mp3downloader.ZingSearch.java
private static String hash_hmac(String data, String key) { try {//from w ww . j a va 2 s. c o m // Get an hmac_sha1 key from the raw key bytes byte[] keyBytes = key.getBytes(); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacMD5"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacMD5"); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.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) { e.printStackTrace(); } return null; }
From source file:com.dongwookchung.nutritioncalculator.FatSecretAPI.java
/** * Returns signature generated using signature base as text and consumer secret as key * * @param method// w w w. j a v a 2s .co m * Http method * @param uri * Request URL - http://platform.fatsecret.com/rest/server.api (Always remains the same) * @param params * An array of parameter values as "key=value" pair * * @return oauth_signature which will be added to request for calling fatsecret api */ public String sign(String method, String uri, String[] params) throws UnsupportedEncodingException { String encodedURI = encode(uri); String encodedParams = encode(paramify(params)); String[] p = { method, encodedURI, encodedParams }; String text = join(p, "&"); String key = APP_SECRET + "&"; SecretKey sk = new SecretKeySpec(key.getBytes(), APP_SIGNATURE_METHOD); String sign = ""; try { Mac m = Mac.getInstance(APP_SIGNATURE_METHOD); m.init(sk); sign = encode(new String(Base64.encode(m.doFinal(text.getBytes()), Base64.DEFAULT)).trim()); } catch (java.security.NoSuchAlgorithmException e) { } catch (java.security.InvalidKeyException e) { } return sign; }
From source file:org.apache.qpid.server.security.auth.sasl.CRAMMD5HexServerTest.java
/** * Since we don't have a CRAM-MD5-HEX implementation client implementation in Java, this method * provides the implementation for first principals. * * @param userId user id/*w w w . j a v a2 s. co m*/ * @param clearTextPassword clear text password * @param serverChallenge challenge from server * * @return challenge response */ private byte[] generateClientResponse(final String userId, final String clearTextPassword, final byte[] serverChallenge) throws Exception { byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(clearTextPassword.getBytes()); char[] hexEncodedDigestedPassword = Hex.encodeHex(digestedPasswordBytes); byte[] hexEncodedDigestedPasswordBytes = new String(hexEncodedDigestedPassword).getBytes(); Mac hmacMd5 = Mac.getInstance("HmacMD5"); hmacMd5.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, "HmacMD5")); final byte[] messageAuthenticationCode = hmacMd5.doFinal(serverChallenge); // Build client response String responseAsString = userId + " " + new String(Hex.encodeHex(messageAuthenticationCode)); byte[] resp = responseAsString.getBytes(); return resp; }
From source file:com.leacox.pusher.Pusher.java
/** * Returns a HMAC/SHA256 representation of the given data. *///from www .j a v a2s .c o m private String hmacsha256Representation(String data) { try { // Create the HMAC/SHA256 key from application secret final SecretKeySpec signingKey = new SecretKeySpec(appSecret.getBytes(), "HmacSHA256"); // Create the message authentication code (MAC) final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); // Process and return data byte[] digest; // @TODO: decide if it's UTF-8 or not... digest = mac.doFinal(data.getBytes("UTF-8")); digest = mac.doFinal(data.getBytes()); // Convert to string BigInteger bigInteger = new BigInteger(1, digest); return String.format("%0" + (digest.length << 1) + "x", bigInteger); } catch (NoSuchAlgorithmException nsae) { // We should never come here, because GAE has HMac SHA256 throw new RuntimeException("No HMac SHA256 algorithm"); //} catch (UnsupportedEncodingException e) { // We should never come here, because UTF-8 should be available //throw new RuntimeException("No UTF-8"); } catch (InvalidKeyException e) { throw new RuntimeException("Invalid key exception while converting to HMac SHA256"); } }
From source file:air.com.snagfilms.utils.Utils.java
public static String getfilmriseParameters() { StringBuilder strBlr = null;/*from w ww. ja v a 2 s .c o m*/ try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); long longs = System.currentTimeMillis(); String timestamp = dateFormat.format(longs); ; String stringToSign = timestamp; // Query uses this string // Compute the signature and base64 encode it. String algorithm = "HmacSHA1"; SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(key); String signature = new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes()))); System.out.println(signature);// required for Query signature = URLEncoder.encode(signature, "UTF-8"); strBlr = new StringBuilder(); strBlr.append(Constants.ACCESS_KEY); strBlr.append("="); strBlr.append(ACCESS_KEY); strBlr.append("&"); strBlr.append(Constants.TIME_STAMP); strBlr.append("="); strBlr.append(timestamp); strBlr.append("&"); strBlr.append(Constants.SIGNATURE); strBlr.append("="); strBlr.append(signature); strBlr.append("&"); strBlr.append(Constants.SITE); strBlr.append("="); strBlr.append(Constants.filmrise); strBlr.append("&"); strBlr.append(Constants.DEVICE); strBlr.append("="); strBlr.append("android"); return strBlr.toString(); } catch (Exception e) { } return null; }
From source file:com.maxpowered.amazon.advertising.api.SignedRequestsHelper.java
/** * You must provide the four values below to initialize the helper. * * @param endpoint//from www .ja v a2 s. c o m * Destination for the requests. * @param associateTag * Your AWS Associate Tag * @param awsAccessKeyId * Your AWS Access Key ID * @param awsSecretKey * Your AWS Secret Key * @throws NoSuchAlgorithmException * if the hashing algorithm is invalid (never) * @throws InvalidKeyException * if the secret key is invalid * @throws UnsupportedEncodingException * if the encoding charset is invalid */ SignedRequestsHelper(final Endpoint endpoint, final String associateTag, final String awsAccessKeyId, final String awsSecretKey) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { if (null == endpoint || endpoint.getAPIdomain().length() == 0) { throw new IllegalArgumentException("endpoint is null or empty"); } if (null == associateTag || associateTag.length() == 0) { throw new IllegalArgumentException("awsAssociateTag is null or empty"); } if (null == awsAccessKeyId || awsAccessKeyId.length() == 0) { throw new IllegalArgumentException("awsAccessKeyId is null or empty"); } if (null == awsSecretKey || awsSecretKey.length() == 0) { throw new IllegalArgumentException("awsSecretKey is null or empty"); } this.endpoint = endpoint.getAPIdomain().toLowerCase(); this.associateTag = associateTag; this.awsAccessKeyId = awsAccessKeyId; this.awsSecretKey = awsSecretKey; final byte[] secretyKeyBytes = this.awsSecretKey.getBytes(UTF8_CHARSET); secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM); mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(secretKeySpec); }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ValidateUsernamePasswordAgainstMlaRest.java
/** {@inheritDoc} */ @Override//from w w w . j a v a 2 s .c o m protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { log.debug("{} Attempting to authenticate user {}", getLogPrefix(), getUsernamePasswordContext().getUsername()); try { // Construct the URL composed of the API root, members method with id value equal // to the username entered in the login form, the API key, and time stamp. StringBuilder urlBuilder = new StringBuilder().append(this.apiRoot).append("members/") .append(getUsernamePasswordContext().getUsername()).append("?").append("key=") .append(this.apiKey).append("×tamp=") .append(String.valueOf(Instant.now().getEpochSecond())); // The signature is created by prepending the GET method with a '&' separator to the // URL and then computing the SHA256 HMAC hash using the key. // StringBuilder baseStringBuilder = new StringBuilder().append("GET").append("&") .append(UriUtils.encode(urlBuilder.toString(), "UTF-8")); Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(this.apiSecret.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secretKey); String signature = Hex .encodeHexString(sha256_HMAC.doFinal(baseStringBuilder.toString().getBytes("UTF-8"))); // Append the signature to the URL. urlBuilder.append("&signature=").append(signature); log.debug("{} MLA query URL is {}", getLogPrefix(), urlBuilder.toString()); // Query the MLA API HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { /* Set default parser as a JSON parser to make casting to class instance easier */ request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(urlBuilder.toString())); HttpResponse response = request.execute(); // Parse the response and create an instance of the MLAMemberObject. MLAMemberObject mlaMembership = response.parseAs(MLAMemberObject.class); List<MLAMemberObjectData> data = mlaMembership.getData(); // The data element, if present, is a list. If not present then the size of the list // is zero and this indicates that the username could not be found. if (data.size() < 1) { log.info("{} User {} is not known to MLA", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Parse out the id, username, password hash, and membership status. String memberId = data.get(0).getId(); String username = data.get(0).getAuthentication().getUsername(); String passwordHash = data.get(0).getAuthentication().getPassword(); String membershipStatus = data.get(0).getAuthentication().getMembership_status(); log.debug("{} MLA returned member Id {}", getLogPrefix(), memberId); log.debug("{} MLA returned username {}", getLogPrefix(), username); log.debug("{} MLA returned password hash {}", getLogPrefix(), passwordHash); log.debug("{} MLA returned membership status {}", getLogPrefix(), membershipStatus); // Non-active members cannot authenticate. if (!new String("active").equals(membershipStatus)) { log.info("{} User {} does not have active status", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Compute the bcrypt hash of the password using the salt sent by the MLA API. String pw_hash = BCrypt.hashpw(getUsernamePasswordContext().getPassword(), passwordHash); log.debug("{} Computed hash {}", getLogPrefix(), pw_hash); // Compare the input username with the password hash returned by the MLA API. if (!pw_hash.equals(passwordHash)) { log.info("{} Invalid password", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.INVALID_CREDENTIALS, AuthnEventIds.INVALID_CREDENTIALS); return; } // Set the username in the context directly because the user may have typed the member number // into the form rather than the username. The member number will work for authentication, // but we always want to return the username as the principal. getUsernamePasswordContext().setUsername(username); // Build the authentication result and proceed. log.info("{} Login by '{}' succeeded", getLogPrefix(), getUsernamePasswordContext().getUsername()); buildAuthenticationResult(profileRequestContext, authenticationContext); ActionSupport.buildProceedEvent(profileRequestContext); // } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InterruptedException e) { } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { log.warn("{} Login by {} produced exception", getLogPrefix(), getUsernamePasswordContext().getUsername(), e); handleError(profileRequestContext, authenticationContext, e, AuthnEventIds.AUTHN_EXCEPTION); } }
From source file:com.comcast.cmb.common.util.AuthUtil.java
public static String generateSignature(URL url, Map<String, String> parameters, String version, String algorithm, String accessSecret) throws Exception { String data = null;/*from w ww . j av a2s.c o m*/ if (version.equals("1")) { data = constructV1DataToSign(parameters); } else if (version.equals("2")) { parameters.put("SignatureMethod", algorithm); data = constructV2DataToSign(url, parameters); } else { return null; } Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(accessSecret.getBytes("UTF-8"), algorithm)); byte[] bytes = mac.doFinal(data.getBytes("UTF-8")); String signature = new String(Base64.encodeBase64(bytes)); return signature; }
From source file:net.alegen.datpass.library.crypto.CryptoManager.java
public String generateHmac(EncryptionOutput encryptionOutput, String password) { final String ctext = encryptionOutput.getCypherText(); final String salt = encryptionOutput.getSalt(); final String iv = encryptionOutput.getIV(); try {/*from ww w.j a v a2 s . c o m*/ // create the hmac key and message MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] hmacKey = md.digest(password.getBytes("UTF-8")); byte[] hmacMessage = (iv + ctext + salt).getBytes("UTF-8"); // generate hmac SecretKeySpec keySpec = new SecretKeySpec(hmacKey, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] result = mac.doFinal(hmacMessage); // return result result = Base64.encodeBase64(result); return new String(result, "UTF-8"); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { log.error("An error occured while generating an HMAC value."); return null; } }
From source file:org.dasein.cloud.cloudstack.CSMethod.java
private byte[] calculateHmac(String data, String key) throws SignatureException { try {//w w w . ja v a 2 s . c o m SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); return mac.doFinal(data.getBytes()); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }