List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.apache.hadoop.security.AccessTokenHandler.java
/** Initialize Mac function */ private synchronized void initMac(AccessKey key) throws IOException { try {//from w w w. ja v a 2s . c o m Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(key.getKey().getBytes(), "HmacSHA1")); key.setMac(mac); } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to initialize Mac for access key, keyID=" + key.getKeyID()) .initCause(e); } }
From source file:net.shopxx.plugin.yeepayPayment.YeepayPaymentPlugin.java
private String hmacDigest(String value, String key) { try {//from ww w .j a va 2s . c o m Mac mac = Mac.getInstance("HmacMD5"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacMD5")); byte[] bytes = mac.doFinal(value.getBytes("UTF-8")); StringBuilder digest = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { digest.append("0"); } digest.append(hex); } return digest.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvalidKeyException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java
/** * Signs a request with a secret/* w w w . j ava2 s . c o m*/ * * @param secret * @param hash_data * @return */ private String signRequest(String secret, String hash_data) { String signature = ""; try { Mac mac = Mac.getInstance(Constants.SIGN_HASH_FUNCTION); SecretKeySpec secret_spec = new SecretKeySpec(Base64.decodeBase64(secret), Constants.SIGN_HASH_FUNCTION); mac.init(secret_spec); signature = Base64.encodeBase64String(mac.doFinal(hash_data.getBytes())); } catch (NoSuchAlgorithmException | InvalidKeyException e) { Logger.getLogger(MtGoxTradeService.class.getName()).log(Level.SEVERE, null, e); } return signature; }
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 www.ja v a 2 s . c o m byte[] hashBytes = enc.doFinal(strBytes); String b64Str = new String(Base64.encodeBase64(hashBytes)); return b64Str.replace('/', '_').replace('+', '-').replaceAll("[=]+$", ""); }
From source file:net.groupbuy.plugin.yeepay.YeepayPlugin.java
/** * Hmac// ww w. j a va 2 s. c om * * @param value * * @param key * * @return */ private String hmacDigest(String value, String key) { try { Mac mac = Mac.getInstance("HmacMD5"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacMD5")); byte[] bytes = mac.doFinal(value.getBytes("UTF-8")); StringBuffer digest = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { digest.append("0"); } digest.append(hex); } return digest.toString(); } catch (Exception e) { return null; } }
From source file:id.pazpo.agent.utils.OAuthHeaderBuilder.java
private String generateSignature(String signatureBase, String accessTokenSecret) throws InvalidKeyException, NoSuchAlgorithmException { Mac mac = Mac.getInstance(ENCRYPTION_ALGO); mac.init(new SecretKeySpec((CONSUMER_SECRET + "&" + accessTokenSecret).getBytes(), ENCRYPTION_ALGO)); mac.update(signatureBase.getBytes()); byte[] res = mac.doFinal(); String signature = new String(Base64.encodeBase64(res)).trim(); Log.d("headers", signature); return signature; }
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./*from w w w .ja v a2 s . c o 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.microsoft.valda.oms.OmsAppender.java
private void sendLog(LoggingEvent event) throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException { //create JSON message JSONObject obj = new JSONObject(); obj.put("LOGBACKLoggerName", event.getLoggerName()); obj.put("LOGBACKLogLevel", event.getLevel().toString()); obj.put("LOGBACKMessage", event.getFormattedMessage()); obj.put("LOGBACKThread", event.getThreadName()); if (event.getCallerData() != null && event.getCallerData().length > 0) { obj.put("LOGBACKCallerData", event.getCallerData()[0].toString()); } else {//from w w w . jav a2 s . co m obj.put("LOGBACKCallerData", ""); } if (event.getThrowableProxy() != null) { obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy())); } else { obj.put("LOGBACKStackTrace", ""); } if (inetAddress != null) { obj.put("LOGBACKIPAddress", inetAddress.getHostAddress()); } else { obj.put("LOGBACKIPAddress", "0.0.0.0"); } String json = obj.toJSONString(); String Signature = ""; String encodedHash = ""; String url = ""; // Todays date input for OMS Log Analytics Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String timeNow = dateFormat.format(calendar.getTime()); // String for signing the key String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs"; byte[] decodedBytes = Base64.decodeBase64(sharedKey); Mac hasher = Mac.getInstance("HmacSHA256"); hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256")); byte[] hash = hasher.doFinal(stringToSign.getBytes()); encodedHash = DatatypeConverter.printBase64Binary(hash); Signature = "SharedKey " + customerId + ":" + encodedHash; url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01"; URL objUrl = new URL(url); HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Log-Type", logType); con.setRequestProperty("x-ms-date", timeNow); con.setRequestProperty("Authorization", Signature); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode != 200) { throw new HTTPException(responseCode); } }
From source file:org.cloudfoundry.identity.uaa.authentication.RubyUserTokenTests.java
private static byte[] sign(String username, long validUntil, SecretKey key) { Mac mac;//from ww w . ja v a2s. c o m try { mac = Mac.getInstance("HMACSHA1"); mac.init(key); } catch (GeneralSecurityException e) { throw new RuntimeException("Failed to create and initialize MAC: ", e); } byte[] bytesToSign = Utf8.encode(username + validUntil); // HexDumpEncoder enc = new HexDumpEncoder(); // System.out.println("Signing bytes: \n" + enc.encode(bytesToSign)); byte[] sig = mac.doFinal(bytesToSign); // System.out.println("Signature is: \n" + enc.encode(sig)); return sig; }