List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.sk89q.craftapi.streaming.StreamingServerClient.java
/** * Handle unauthenticated packets.// w w w.j ava 2 s. c o m * * @param parts */ public void handleUnauthenticated(String[] parts) throws UnsupportedEncodingException { String command = decode(parts[0]); // getChallenge if (command.equals("REQC")) { send("CHAL", base64.encodeToString(challenge)); // challengeLogin } else if (command.equals("AUTH")) { try { SecretKey key = new SecretKeySpec(challenge, "HMACSHA256"); Mac mac = Mac.getInstance("HMACSHA256"); mac.init(key); byte[] digest = base64.decode(decode(parts[3]).getBytes()); if (server.getAuthenticationProvider().verifyCredentials(mac, parts[2], digest)) { send("AUTHOK"); state = State.READY; } else { sendError(ERROR_AUTHENTICATION); } } catch (NoSuchAlgorithmException e) { sendError(ERROR_INTERNAL, e.getMessage()); } catch (InvalidKeyException e) { sendError(ERROR_INTERNAL, e.getMessage()); } // Unknown } else { sendError(ERROR_UNKNOWN_PACKET, command); } }
From source file:org.apache.sshd.common.util.SecurityUtils.java
public static synchronized Mac getMac(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException { register();//from w w w. ja v a 2 s.com if (getSecurityProvider() == null) { return Mac.getInstance(algorithm); } else { return Mac.getInstance(algorithm, getSecurityProvider()); } }
From source file:org.broadleafcommerce.vendor.authorizenet.service.payment.AuthorizeNetCheckoutServiceImpl.java
@Override public String createTamperProofSeal(String customerId, String orderId) throws NoSuchAlgorithmException, InvalidKeyException { String transactionKey = configuration.getTransactionKey(); Base64 encoder = new Base64(); Mac sha1Mac = Mac.getInstance("HmacSHA1"); SecretKeySpec publicKeySpec = new SecretKeySpec(transactionKey.getBytes(), "HmacSHA1"); sha1Mac.init(publicKeySpec);// w w w . j ava 2s. c o m String customerOrderString = customerId + orderId; byte[] publicBytes = sha1Mac.doFinal(customerOrderString.getBytes()); String publicDigest = encoder.encodeToString(publicBytes); return publicDigest.replaceAll("\\r|\\n", ""); }
From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java
private boolean validateSignatureV1(Map<String, String> parameters) throws SignatureException { if (this.awsSecretKey == null) { throw new SignatureException("Signature can not be verified without aws secret key."); }/*from w ww . jav a 2s.c o m*/ String stringToSign = calculateStringToSignV1(parameters); String signature = parameters.get(SIGNATURE_KEYNAME); String result; try { SecretKeySpec signingKey = new SecretKeySpec(this.awsSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(stringToSign.getBytes("UTF-8")); result = new String(Base64.encodeBase64(rawHmac)); } catch (NoSuchAlgorithmException e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } catch (InvalidKeyException e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result.equals(signature); }
From source file:org.mitre.jwt.signer.impl.HmacSigner.java
private void initializeMac() { if (mac == null) { try {/*from w w w. j a va2 s. c o m*/ mac = Mac.getInstance(getAlgorithm().getStandardName()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.runtimecollective.influence.metrics.Alexa.java
/** * Computes RFC 2104-compliant HMAC signature. * //from w w w . java2 s . c om * @param data * The data to be signed. * @param key * The signing key. * @return * The Base64-encoded RFC 2104-compliant HMAC signature. * @throws * java.security.SignatureException when signature generation fails */ private String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac result = new sun.misc.BASE64Encoder().encode(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
From source file:com.lambdasoup.panda.PandaHttp.java
private static String generateSignature(String method, String url, String host, String secretKey, Map<String, String> params) { String queryString = canonicalQueryString(params); String stringToSign = method.toUpperCase() + "\n" + host + "\n" + url + "\n" + queryString; String signature = null;//from w w w . j a v a 2 s .c om try { SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(stringToSign.getBytes()); signature = new String(Base64.encodeBase64(rawHmac)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return signature; }
From source file:org.apache.hadoop.hdfs.security.AccessTokenHandler.java
/** Initialize Mac function */ private synchronized void initMac(BlockAccessKey key) throws IOException { try {/*from w w w . java 2 s . c om*/ 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:org.springframework.social.facebook.web.RealTimeUpdateController.java
private boolean verifySignature(String payload, String signature) throws Exception { if (!signature.startsWith("sha1=")) { return false; }// w ww. j av a2 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:io.teak.sdk.Request.java
@Override public void run() { HttpsURLConnection connection = null; SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256"); String requestBody;//from ww w . j a v a 2s .c o m String hostnameForEndpoint = this.hostname; if (hostnameForEndpoint == null) { hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint); } try { ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet()); Collections.sort(payloadKeys); StringBuilder builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); if (value != null) { String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(valueString).append("&"); } else { Log.e(LOG_TAG, "Value for key: " + key + " is null."); } } builder.deleteCharAt(builder.length() - 1); String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] result = mac.doFinal(stringToSign.getBytes()); builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&"); } builder.append("sig=") .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8")); requestBody = builder.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e)); return; } try { if (Teak.isDebug) { Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': " + new JSONObject(this.payload).toString(2)); } URL url = new URL("https://" + hostnameForEndpoint + this.endpoint); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // Get Response InputStream is; if (connection.getResponseCode() < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (Teak.isDebug) { String responseText = response.toString(); try { responseText = new JSONObject(response.toString()).toString(2); } catch (Exception ignored) { } Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText); } // For extending classes done(connection.getResponseCode(), response.toString()); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } }