List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:com.cloud.stack.CloudStackCommand.java
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException { String result = null;/*from w w w. jav a2s. co m*/ try { SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); Mac hmacSha1 = Mac.getInstance("HmacSHA1"); hmacSha1.init(key); byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes()); result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate keyed HMAC on soap request: " + e.getMessage()); } return result.trim(); }
From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContextTest.java
/** * Validates the checksum of the given url. * @param url The source for the checksum validation. * @param checksum The checksum./* w w w . j a va 2 s . co m*/ * @return true if valid, false otherwise. * @throws Exception */ protected boolean validateChecksum(final String url, final String checksum) throws Exception { SecretKey macKey = new SecretKeySpec(sharedSecret.getBytes("UTF-8"), WilmaAuthenticationContext.MAC_ALGORITHM); Mac mac = Mac.getInstance(WilmaAuthenticationContext.MAC_ALGORITHM); mac.init(macKey); byte[] digest = mac.doFinal(url.getBytes("UTF-8")); return Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest); }
From source file:com.diversityarrays.dalclient.DalUtil.java
/** * Calculate an RFC 2104 compliant HMAC signature. * @param key is the signing key//from ww w .j a v a 2 s . c om * @param data is the data to be signed * @return the base64-encoded signature as a String */ public static String computeHmacSHA1(String key, String data) { try { byte[] keyBytes = key.getBytes(cryptCharsetName); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, ALGORITHM_HMAC_SHA1); Mac mac = Mac.getInstance(ALGORITHM_HMAC_SHA1); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes(cryptCharsetName)); byte[] hexBytes = new Hex().encode(rawHmac); return new String(hexBytes, cryptCharsetName); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:de.hybris.platform.acceleratorservices.payment.utils.impl.DefaultAcceleratorDigestUtils.java
@Override public String getPublicDigest(final String customValues, final String key) throws NoSuchAlgorithmException, InvalidKeyException { final Base64 encoder = new Base64(); final Mac sha1Mac = Mac.getInstance(getMacAlgorithm()); final SecretKeySpec publicKeySpec = new SecretKeySpec(key.getBytes(), getMacAlgorithm()); sha1Mac.init(publicKeySpec);//from w w w.ja v a2 s . c o m final byte[] publicBytes = sha1Mac.doFinal(customValues.getBytes()); final String publicDigest = new String(encoder.encode(publicBytes)); return publicDigest.replaceAll("\n", ""); }
From source file:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java
protected String hashRequestBody(HttpServletRequest request, SecretKey secretKey) throws IOException, ServletException { final byte[] result; try {/* w ww. j ava 2s .c o m*/ final Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); result = mac.doFinal(IOUtils.toByteArray(request.getInputStream())); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } catch (InvalidKeyException e) { throw new ServletException(e); } return new String(Hex.encodeHex(result)); }
From source file:com.spartan.springmvc.bean.FacebookSignatureBean.java
/** * Parses and verifies a Facebook signed_request parameter. The data of the signed request is returned on successful verification. * * @param signedRequest/*from w w w .j ava 2s .c o m*/ * @param appSecret * @return * @return * @throws FacebookSignatureVerificationFailedException */ @SuppressWarnings("unchecked") public <T> T parseSignature(String signedRequest, String appSecret, Class<T> clazz) throws FacebookSignatureVerificationFailedException { String[] parts = signedRequest.split("\\."); if (parts.length != 2) { throw new FacebookSignatureVerificationFailedException("Invalid signature format."); } String encSig = parts[0]; String encPayload = parts[1]; Base64 decoder = new Base64(true); try { Mac mac = Mac.getInstance("HMACSHA256"); mac.init(new SecretKeySpec(appSecret.getBytes(), mac.getAlgorithm())); byte[] calcSig = mac.doFinal(encPayload.getBytes()); byte[] decodedSig = decoder.decode(encSig); boolean isVerified = Arrays.equals(decodedSig, calcSig); if (isVerified) { try { String unsignedData = new String(decoder.decode(encPayload)); logger.debug("unsignedData: " + unsignedData); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); T data = mapper.readValue(unsignedData, (Class<T>) clazz); return data; } catch (IOException e) { throw new FacebookSignatureVerificationFailedException( "Failed to parse JSON data: " + e.getMessage(), e); } } else { throw new FacebookSignatureVerificationFailedException("Signatures do not match."); } } catch (NoSuchAlgorithmException e) { throw new FacebookSignatureVerificationFailedException(e); } catch (InvalidKeyException e) { throw new FacebookSignatureVerificationFailedException(e); } }
From source file:com.torchmind.authenticator.AbstractTokenGenerator.java
/** * Generates a code based on a secret key and challenge. * * @param secretKey a secret key./* w w w .ja v a2 s. co m*/ * @param challenge a challenge. * @return a code. */ @NonNull protected String generateCode(@NonNull SecretKey secretKey, @NonNull byte[] challenge) { try { Mac mac = Mac.getInstance("Hmac" + this.algorithm.name()); mac.init(secretKey); byte[] hash = mac.doFinal(challenge); int offset = hash[hash.length - 1] & 0x0F; ByteBuffer buffer = ByteBuffer.allocate(4).put(hash, offset, 4); buffer.flip(); return String.format("%0" + this.digits + "d", (buffer.getInt() & 0x7FFFFFFF) % this.digitModulo); } catch (NoSuchAlgorithmException ex) { throw new UnsupportedOperationException( "The specified algorithm is not supported by this Java VM implementation: " + ex.getMessage(), ex); } catch (InvalidKeyException ex) { throw new IllegalArgumentException("Invalid shared secret: " + ex.getMessage(), ex); } }
From source file:com.pliu.powerbiembed.ReportController.java
private String HMAC256EncryptBase64UrlEncode(String str, String accessKey) throws Exception { byte[] key = accessKey.getBytes("UTF-8"); byte[] strBytes = str.getBytes("UTF-8"); Mac enc = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key, "HmacSHA256"); enc.init(secret_key);//from w w w. ja v a2s .c o m byte[] hashBytes = enc.doFinal(strBytes); String b64Str = new String(Base64.encodeBase64(hashBytes)); return b64Str.replace('/', '_').replace('+', '-').replaceAll("[=]+$", ""); }
From source file:com.adyen.Util.HMACValidator.java
public String calculateHMAC(String data, String key) throws java.security.SignatureException { try {//from ww w.jav a 2 s .co m byte[] rawKey = Hex.decodeHex(key.toCharArray()); // Create an hmac_sha256 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(rawKey, HMAC_SHA256_ALGORITHM); // Get an hmac_sha256 Mac instance and initialize with the signing // key Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes(C_UTF8)); // Base64-encode the hmac return new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }
From source file:fitmon.WorkoutApi.java
public StringBuilder apiGetInfo() throws ClientProtocolException, IOException, NoSuchAlgorithmException, InvalidKeyException { HttpClient client = new DefaultHttpClient(); //HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&" // + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&" // + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=4384"); //HttpResponse response = client.execute(request); //BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); //StringBuilder sb = new StringBuilder(); String base = URLEncoder.encode("GET") + "&"; base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; String params;/* www .j av a2s . c o m*/ params = "format=json&"; params += "method=exercises.get&"; 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=apple"; 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); HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature=" + URLEncoder.encode(hash)); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder sb = new StringBuilder(); //$url = "http://platform.fatsecret.com/rest/server.api?"+params+"&oauth_signature="+URLEncoder.encode(hash); //return url; while ((line = rd.readLine()) != null) { sb.append(line); //System.out.println(line); } //System.out.println(sb.toString()); return sb; }