List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
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 w w w . j ava2s .co 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:me.whitmarbut.mfa.TOTP.java
private byte[] getHmac(int timestamp, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec key_spec = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key_spec);/*from ww w . jav a 2 s. co m*/ byte[] bin_timestamp = ByteBuffer.allocate(4).putInt(timestamp).array(); ByteBuffer bbuff = ByteBuffer.allocate(8); bbuff.putInt(0); //Left pad 4 bytes to make a 64 bit int bbuff.putInt(timestamp); return mac.doFinal(bbuff.array()); }
From source file:br.com.argonavis.jaspictut.service.FacebookConnectService.java
/** * Source: https://jira.spring.io/browse/SOCIALFB-148 * @param token/* w w w .j a va2 s .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.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java
private String signedCall(String endPoint, Map<String, String> params, String reqId) throws JsonProcessingException, UnsupportedEncodingException { long nonce = MtGoxUtils.getNonce(); HashMap<String, Object> call = new HashMap<String, Object>(6); call.put("id", reqId); call.put("call", endPoint); call.put("nonce", nonce); call.put("params", params); ObjectMapper mapper = new ObjectMapper(); String callString = mapper.writeValueAsString(call); String signedCall = null;//from w w w. ja va 2 s . c o m try { byte[] bsecret = Base64.decode(this.apiSecret); SecretKeySpec spec = new SecretKeySpec(bsecret, "HmacSHA512"); Mac mac = Mac.getInstance("HmacSHA512"); mac.init(spec); byte[] bsig = mac.doFinal(callString.getBytes()); byte[] keyB = fromHexString(this.apiKey.replaceAll("-", "")); byte[] callB = callString.getBytes(); byte[] c = new byte[bsig.length + keyB.length + callB.length]; System.arraycopy(keyB, 0, c, 0, keyB.length); System.arraycopy(bsig, 0, c, keyB.length, bsig.length); System.arraycopy(callB, 0, c, keyB.length + bsig.length, callB.length); signedCall = Base64.encodeBytes(c); } catch (Exception e) { System.out.println("e!: " + e); } HashMap<String, String> msg = new HashMap<String, String>(4); msg.put("op", "call"); msg.put("call", signedCall); msg.put("id", reqId); msg.put("context", "mtgox.com"); mapper = new ObjectMapper(); return mapper.writeValueAsString(msg); }
From source file:org.springframework.social.facebook.web.RealTimeUpdateController.java
private boolean verifySignature(String payload, String signature) throws Exception { if (!signature.startsWith("sha1=")) { return false; }//from w w w . j ava 2 s. c o m String expected = signature.substring(5); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); SecretKeySpec signingKey = new SecretKeySpec(applicationSecret.getBytes(), HMAC_SHA1_ALGORITHM); mac.init(signingKey); byte[] rawHmac = mac.doFinal(payload.getBytes()); String actual = new String(Hex.encode(rawHmac)); return expected.equals(actual); }
From source file:fitmon.DietAPI.java
public ArrayList<Food> getFood(String foodID) throws ClientProtocolException, IOException, NoSuchAlgorithmException, InvalidKeyException, SAXException, ParserConfigurationException { 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=33691"); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String base = URLEncoder.encode("GET") + "&"; base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; String params;// ww w . jav a 2 s . co m params = "food_id=" + foodID + "&"; params += "method=food.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); String url = "http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature=" + URLEncoder.encode(hash); System.out.println(url); xmlParser xParser = new xmlParser(); ArrayList<Food> foodList = xParser.Parser(url); return foodList; //while ((line = rd.readLine()) != null) { // System.out.println(line); //} }
From source file:fi.okm.mpass.shibboleth.authn.impl.ValidateWilmaResponse.java
/** {@inheritDoc} */ @Override// www . j a va 2 s. co m protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { final HttpServletRequest servletRequest = getHttpServletRequest(); final WilmaAuthenticationContext wilmaContext = authenticationContext .getSubcontext(WilmaAuthenticationContext.class, false); final String nonce = wilmaContext.getNonce(); if (!getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE).equals(nonce)) { log.warn("{}: Invalid nonce in the incoming Wilma response!", getLogPrefix()); log.debug("{} vs {}", nonce, getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE)); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } final String checksum = getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_CHECKSUM); final String query = servletRequest.getQueryString().substring(0, servletRequest.getQueryString() .indexOf("&" + WilmaAuthenticationContext.PARAM_NAME_CHECKSUM + "=")); final String url = servletRequest.getRequestURL().append("?").append(query).toString(); try { final Mac mac = Mac.getInstance(algorithm); mac.init(macKey); byte[] digest = mac.doFinal(url.getBytes("UTF-8")); if (!Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest)) { log.warn("{}: The checksum validation failed for user {}", getLogPrefix(), getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID)); log.trace("{} (params) vs {}", checksum, new String(Hex.encodeHex(digest))); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException | UnsupportedEncodingException | IllegalArgumentException e) { log.error("{}: Could not verify the checksum {}", getLogPrefix(), checksum, e); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } log.trace("{}: Building authentication result for user {}", getLogPrefix(), getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID)); buildAuthenticationResult(profileRequestContext, authenticationContext); }
From source file:com.kolich.aws.signing.impl.KolichAwsSigner.java
@Override public final String sign(final AwsCredentials credentials, final String input) { try {/* w ww . j a v a2 s . co m*/ final String algoName = algorithm_.toString(); // Get a new instance of the HMAC-SHA1 algorithm. final Mac mac = Mac.getInstance(algoName); // Init it with our secret and the secret-key algorithm. mac.init(new SecretKeySpec(credentials.getSecretBytes(), algoName)); // Sign the input. return encodeBase64ToString(mac.doFinal(getBytesUtf8(input))); } catch (Exception e) { throw new KolichAwsException( "Failed to sign input " + "string (algorithm=" + algorithm_ + ", input=" + input + ")", e); } }
From source file:lumbermill.internal.aws.AWSV4SignerImpl.java
private byte[] hmacSHA256(String data, byte[] key) { try {/*w w w . ja v a2s .c o m*/ final Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(new SecretKeySpec(key, HMAC_SHA256)); return mac.doFinal(data.getBytes(Charsets.UTF_8)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw Throwables.propagate(e); } }
From source file:net.sf.xfd.provider.PublicProvider.java
public static @Nullable Uri publicUri(Context context, CharSequence path, String mode) { // XXX suspect coversion final String pathString = path.toString(); final int modeInt = ParcelFileDescriptor.parseMode(mode); final Key key = getSalt(context); if (key == null) { return null; }/*from ww w . j a v a2s. co m*/ final Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); final long l = c.getTimeInMillis(); final byte[] encoded; try { final Mac hash = Mac.getInstance("HmacSHA1"); hash.init(key); final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16), (byte) (modeInt >> 8), (byte) modeInt, }; hash.update(modeBits); final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40), (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, }; hash.update(expiryDate); encoded = hash.doFinal(pathString.getBytes()); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError("Error while creating a hash: " + e.getMessage(), e); } final String packageName = context.getPackageName(); final Uri.Builder b = new Uri.Builder().scheme(SCHEME_CONTENT).authority(packageName + AUTHORITY_SUFFIX); if (!"r".equals(mode)) { b.appendQueryParameter(URI_ARG_MODE, mode); } return b.path(pathString).appendQueryParameter(URI_ARG_EXPIRY, String.valueOf(l)) .appendQueryParameter(URI_ARG_COOKIE, encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING)) .build(); }