List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.springframework.social.facebook.web.SignedRequestDecoder.java
private byte[] encrypt(String base, String key) { try {//from w ww. ja v a 2 s. c o m SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), HMAC_SHA256_MAC_NAME); Mac mac = Mac.getInstance(HMAC_SHA256_MAC_NAME); mac.init(secretKeySpec); return mac.doFinal(base.getBytes()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (InvalidKeyException e) { throw new IllegalStateException(e); } }
From source file:br.com.argonavis.jaspictut.service.FacebookConnectService.java
/** * Source: https://jira.spring.io/browse/SOCIALFB-148 * @param token//from www . j a v a 2s.c om * @param appSecret * @return * @throws Exception */ private String calculateAppSecretProof(String token, String appSecret) { try { Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"); mac.init(secretKey); byte[] digest = mac.doFinal(token.getBytes()); return new String(Hex.encodeHex(digest)); } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException ex) { Logger.getLogger(FacebookConnectService.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:com.akamai.edgegrid.signer.EdgeGridV1Signer.java
private static byte[] sign(String s, byte[] key) throws RequestSigningException { try {/*from www. ja v a2 s . c o m*/ SecretKeySpec signingKey = new SecretKeySpec(key, SIGNING_ALGORITHM); Mac mac = Mac.getInstance(SIGNING_ALGORITHM); mac.init(signingKey); byte[] valueBytes = s.getBytes(StandardCharsets.UTF_8); return mac.doFinal(valueBytes); } catch (NoSuchAlgorithmException e) { throw new RequestSigningException( "Failed to sign: your JDK does not recognize signing algorithm <" + SIGNING_ALGORITHM + ">", e); } catch (InvalidKeyException e) { throw new RequestSigningException("Failed to sign: invalid key", e); } }
From source file:fitmon.DietAPI.java
public ArrayList<ArrayList<Food>> searchFood(String foodName) throws InvalidKeyException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException { xmlParser xParser = new xmlParser(); ArrayList<ArrayList<Food>> listOfFoodList = new ArrayList<ArrayList<Food>>(); ArrayList<String> list; String base = URLEncoder.encode("GET") + "&"; base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; String params;/*from www . j av a 2 s . c o m*/ //params = "format=json&"; params = "method=foods.search&"; params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key params += "oauth_nonce=123&"; params += "oauth_signature_method=HMAC-SHA1&"; Date date = new java.util.Date(); Timestamp ts = new Timestamp(date.getTime()); params += "oauth_timestamp=" + ts.getTime() + "&"; params += "oauth_version=1.0&"; params += "search_expression=" + foodName; String params2 = URLEncoder.encode(params); base += params2; System.out.println(base); String line = ""; String secret = "76172de2330a4e55b90cbd2eb44f8c63&"; Mac sha256_HMAC = Mac.getInstance("HMACSHA1"); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1"); sha256_HMAC.init(secret_key); String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes())); //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); String url = "http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature=" + URLEncoder.encode(hash); System.out.println(url); list = xParser.foodSearchParser(url); for (int i = 0; i < list.size(); i++) { listOfFoodList.add(getFood(list.get(i))); } return listOfFoodList; }
From source file:net.webpasswordsafe.server.plugin.authentication.TwoStepTOTPAuthenticator.java
private int calculateCode(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException { byte[] data = new byte[8]; long value = t; for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; }/*from ww w.ja v a 2s.c om*/ SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; return (int) truncatedHash; }
From source file:de.anycook.social.facebook.FacebookHandler.java
public static boolean verifySigSHA256(String sig, String payload) { try {/* w w w . j a v a2 s. c om*/ Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secret = new SecretKeySpec(APP_SECRET.getBytes(), "HmacSHA256"); mac.init(secret); byte[] digest = mac.doFinal(payload.getBytes()); String expected_sig = new String(digest); if (sig.equals(expected_sig)) { return true; } } catch (NoSuchAlgorithmException | InvalidKeyException e) { LOGGER.error(e, e); } LOGGER.error("signatures are not the same!"); return false; }
From source file:com.xerox.amazonws.common.AWSConnection.java
/** * Calculate the HMAC/SHA1 on a string./*from w w w. j a v a 2s.c o m*/ * @param awsSecretKey passcode to sign it with * @param canonicalString data to sign * @return signature * @throws NoSuchAlgorithmException If the algorithm does not exist. Unlikely * @throws InvalidKeyException If the key is invalid. */ protected String encode(String awsSecretKey, String canonicalString, boolean urlencode) { // The following HMAC/SHA1 code for the signature is taken from the // AWS Platform's implementation of RFC2104 (amazon.webservices.common.Signature) // // Acquire an HMAC/SHA1 from the raw key bytes. SecretKeySpec signingKey = new SecretKeySpec(awsSecretKey.getBytes(), "HmacSHA1"); // Acquire the MAC instance and initialize with the signing key. if (mac == null || !lastSecretKey.equals(awsSecretKey)) { try { mac = Mac.getInstance("HmacSHA1"); } catch (NoSuchAlgorithmException e) { // should not happen throw new RuntimeException("Could not find sha1 algorithm", e); } try { mac.init(signingKey); } catch (InvalidKeyException e) { // also should not happen mac = null; throw new RuntimeException("Could not initialize the MAC algorithm", e); } lastSecretKey = awsSecretKey; } // Compute the HMAC on the digest, and set it. byte[] signedBytes = null; synchronized (mac) { signedBytes = mac.doFinal(canonicalString.getBytes()); } String b64 = new String(Base64.encodeBase64(signedBytes)); if (urlencode) { return urlencode(b64); } else { return b64; } }
From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.SignatureGenerator.java
public String getSignature(String secretKey) { Mac mac;// ww w . jav a 2s . com try { mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(secretKey.getBytes(), ALGORITHM)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } mac.update(method.getBytes()); mac.update((byte) '\n'); mac.update(host.getBytes()); mac.update((byte) '\n'); mac.update(path.getBytes()); mac.update((byte) '\n'); boolean addAmpersand = false; for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { byte[] nameBytes = encodeString(entry.getKey()); List<String> values = entry.getValue(); Collections.sort(values); for (String value : values) { if (addAmpersand) { mac.update((byte) '&'); } else { addAmpersand = true; } byte[] valueBytes = encodeString(value); mac.update(nameBytes); mac.update((byte) '='); mac.update(valueBytes); } } byte[] digest = mac.doFinal(); return new String(Base64.encodeBase64(digest)); }
From source file:com.appdynamics.cloudstack.CloudStackApiClient.java
public String calculateRFC2104HMAC(String data, String key) throws Exception { String result;/*from ww w .j a v a 2 s . c om*/ try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac // result = Base64.encode(rawHmac); result = new String(Base64.encodeBase64(rawHmac)); return result.trim(); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } // return encodeUrl(result); }
From source file:nl.esciencecenter.octopus.webservice.mac.MacScheme.java
/** * Computes RFC 2104-compliant HMAC signature. * * @param data//ww w. j ava2 s.c om * The data to be signed. * @param key * The signing key. * @param algorithm * MAC algorithm implemented by javax.crypto.MAC * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws AuthenticationException * when signature generation fails */ private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException { try { Mac mac = Mac.getInstance(algorithm); SecretKeySpec macKey = new SecretKeySpec(key.getBytes(), "RAW"); mac.init(macKey); byte[] signature = mac.doFinal(data.getBytes()); return Base64.encodeBase64String(signature); } catch (InvalidKeyException e) { throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AuthenticationException("Algorithm is not supported", e); } }