List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:com.emc.atmos.api.test.AtmosApiClientTest.java
@Test public void testHmac() throws Exception { // Compute the signature hash String input = "Hello World"; byte[] secret = Base64.decodeBase64("D7qsp4j16PBHWSiUbc/bt3lbPBY=".getBytes("UTF-8")); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1"); mac.init(key); l4j.debug("Hashing: \n" + input); byte[] hashData = mac.doFinal(input.getBytes("ISO-8859-1")); // Encode the hash in Base64. String hashOut = new String(Base64.encodeBase64(hashData), "UTF-8"); l4j.debug("Hash: " + hashOut); }
From source file:com.MainFiles.Functions.java
public String encryptPin(String username, String plainPassword, String strKey) { String plainString = username + plainPassword; byte[] byteArray = Base64.encodeBase64(plainString.getBytes()); String encodedString = new String(byteArray); String HMAC_SHA512 = "HmacSHA512"; String DEFAULT_ENCODING = "UTF-8"; byte[] result = null; //Hash Algorithm try {/*from w w w. j ava 2 s.c o m*/ SecretKeySpec keySpec = new SecretKeySpec(strKey.getBytes(DEFAULT_ENCODING), HMAC_SHA512); Mac mac = Mac.getInstance(HMAC_SHA512); mac.init(keySpec); result = mac.doFinal(encodedString.getBytes(DEFAULT_ENCODING)); } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException ex) { this.log("INFO strResponseFooter() ::" + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "ERROR"); } StringBuilder sb = new StringBuilder(); for (byte b : result) { sb.append(String.format("%02X", b)); } return sb.toString(); }
From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java
/** * Computes RFC 2104-compliant HMAC signature. * */// w w w . j ava 2 s. c o m private String sign(String data, String key, String algorithm) throws SignatureException { byte[] signature; try { Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key.getBytes(), algorithm)); signature = Base64.encodeBase64(mac.doFinal(data.getBytes(DEFAULT_ENCODING))); } catch (Exception e) { throw new SignatureException("Failed to generate signature: " + e.getMessage(), e); } return new String(signature); }
From source file:de.andreas_rueckert.trade.site.cryptsy.client.CryptsyClient.java
/** * Execute a authenticated query on cryptsy. * * @param method The method to execute. * @param arguments The arguments to pass to the server. * @param userAccount The user account on the exchange, or null if the default account should be used. * @return The returned data as JSON or null, if the request failed. *///from ww w .ja va2 s . co m private final JSON authenticatedHTTPRequest(String method, Map<String, String> arguments, TradeSiteUserAccount userAccount) { HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines. Mac mac; SecretKeySpec key = null; String accountKey = null; // The used key of the account. String accountSecret = null; // The used secret of the account. // Try to get an account key and secret for the request. if (userAccount != null) { accountKey = userAccount.getAPIkey(); accountSecret = userAccount.getSecret(); } else if (_defaultUserAccount != null) { // Use the default values from the API implementation. accountKey = _defaultUserAccount.getAPIkey(); accountSecret = _defaultUserAccount.getSecret(); } // Check, if account key and account secret are available for the request. if (accountKey == null) { throw new MissingAccountDataException("Public key not available for authenticated request to " + _name); } if (accountSecret == null) { throw new MissingAccountDataException( "Private key not available for authenticated request to " + _name); } if (arguments == null) { // If the user provided no arguments, just create an empty argument array. arguments = new HashMap<String, String>(); } arguments.put("method", method); // Add the method to the post data. arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce. // Convert the arguments into a string to post them. String postData = ""; for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) { Map.Entry argument = (Map.Entry) argumentIterator.next(); if (postData.length() > 0) { postData += "&"; } postData += argument.getKey() + "=" + argument.getValue(); } // Create a new secret key try { key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512"); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } // Create a new mac try { mac = Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException nsae) { System.err.println("No such algorithm exception: " + nsae.toString()); return null; } // Init mac with key. try { mac.init(key); } catch (InvalidKeyException ike) { System.err.println("Invalid key exception: " + ike.toString()); return null; } // Add the key to the header lines. headerLines.put("Key", accountKey); // Encode the post data by the secret and encode the result as base64. try { headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8")))); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } // Now do the actual request String requestResult = HttpUtils.httpPost(_url, headerLines, postData); if (requestResult != null) { // The request worked try { // Convert the HTTP request return value to JSON to parse further. JSONObject jsonResult = JSONObject.fromObject(requestResult); // Check, if the request was successful int success = jsonResult.getInt("success"); if (success == 0) { // The request failed. String errorMessage = jsonResult.getString("error"); LogUtils.getInstance().getLogger().error(_name + " trade API request failed: " + errorMessage); return null; } else { // Request succeeded! // Try to figure, what the return actually is: json object or json array? // Test, if the return value is an JSONArray. JSONArray arrayReturn = jsonResult.optJSONArray("return"); if (arrayReturn != null) { // Converting the result into a JSON array worked, so return it. return arrayReturn; } // Now test, if the return value is a JSONObject. JSONObject objectReturn = jsonResult.optJSONObject("return"); if (objectReturn != null) { // Converting the result into a JSON object worked, so return it. return objectReturn; } if (!jsonResult.has("return")) { // Has this object no return value? LogUtils.getInstance().getLogger() .error(_name + " trade API request '" + method + "' has no return value."); return null; // No reasonable return value possible. } else { // There is a return value, but it's neither an array or a object, so we cannot convert it. LogUtils.getInstance().getLogger().error(_name + " trade API request '" + method + "' has a return value, that is neither a JSONObject or a JSONArray. Don't know, what to do with it."); return null; // Not much we can do here... } } } catch (JSONException je) { System.err.println("Cannot parse json request result: " + je.toString()); return null; // An error occured... } } return null; // The request failed. }
From source file:com.cloud.server.ManagementServerImpl.java
private String signRequest(String request, String key) { try {//from w w w. j av a2 s. co m s_logger.info("Request: " + request); s_logger.info("Key: " + key); if (key != null && request != null) { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); return new String((Base64.encodeBase64(encryptedBytes))); } } catch (Exception ex) { s_logger.error("unable to sign request", ex); } return null; }
From source file:de.andreas_rueckert.trade.site.btc_e.client.BtcEClient.java
/** * Execute a authenticated query on btc-e. * * @param method The method to execute.// w ww.j ava 2 s . c o m * @param arguments The arguments to pass to the server. * @param userAccount The user account on the exchange, or null if the default account should be used. * * @return The returned data as JSON or null, if the request failed. * * @see http://pastebin.com/K25Nk2Sv */ private final JSONObject authenticatedHTTPRequest(String method, Map<String, String> arguments, TradeSiteUserAccount userAccount) { HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines. Mac mac; SecretKeySpec key = null; String accountKey; // The used key of the account. String accountSecret; // The used secret of the account. // Try to get an account key and secret for the request. if (userAccount != null) { accountKey = userAccount.getAPIkey(); accountSecret = userAccount.getSecret(); } else { // Use the default values from the API implementation. accountKey = _key; accountSecret = _secret; } // Check, if account key and account secret are available for the request. if (accountKey == null) { throw new MissingAccountDataException("Key not available for authenticated request to btc-e"); } if (accountSecret == null) { throw new MissingAccountDataException("Secret not available for authenticated request to btc-e"); } if (arguments == null) { // If the user provided no arguments, just create an empty argument array. arguments = new HashMap<String, String>(); } arguments.put("method", method); // Add the method to the post data. arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce. // Convert the arguments into a string to post them. String postData = ""; for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) { Map.Entry argument = (Map.Entry) argumentIterator.next(); if (postData.length() > 0) { postData += "&"; } postData += argument.getKey() + "=" + argument.getValue(); } // Create a new secret key try { key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512"); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } // Create a new mac try { mac = Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException nsae) { System.err.println("No such algorithm exception: " + nsae.toString()); return null; } // Init mac with key. try { mac.init(key); } catch (InvalidKeyException ike) { System.err.println("Invalid key exception: " + ike.toString()); return null; } // Add the key to the header lines. headerLines.put("Key", accountKey); // Encode the post data by the secret and encode the result as base64. try { headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8")))); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } // Now do the actual request String requestResult = HttpUtils.httpPost("https://" + DOMAIN + "/tapi", headerLines, postData); if (requestResult != null) { // The request worked try { // Convert the HTTP request return value to JSON to parse further. JSONObject jsonResult = JSONObject.fromObject(requestResult); // Check, if the request was successful int success = jsonResult.getInt("success"); if (success == 0) { // The request failed. String errorMessage = jsonResult.getString("error"); LogUtils.getInstance().getLogger().error("btc-e.com trade API request failed: " + errorMessage); return null; } else { // Request succeeded! return jsonResult.getJSONObject("return"); } } catch (JSONException je) { System.err.println("Cannot parse json request result: " + je.toString()); return null; // An error occured... } } return null; // The request failed. }
From source file:carnero.cgeo.original.libs.Base.java
public static byte[] hashHmac(String text, String salt) { byte[] macBytes = {}; try {/* ww w . j a va 2 s . co m*/ SecretKeySpec secretKeySpec = new SecretKeySpec(salt.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKeySpec); macBytes = mac.doFinal(text.getBytes()); } catch (Exception e) { Log.e(Settings.tag, "cgBase.hashHmac: " + e.toString()); } return macBytes; }
From source file:carnero.cgeo.cgBase.java
public static byte[] hashHmac(String text, String salt) { byte[] macBytes = {}; try {//from w w w . ja va2 s .c o m SecretKeySpec secretKeySpec = new SecretKeySpec(salt.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKeySpec); macBytes = mac.doFinal(text.getBytes()); } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.hashHmac: " + e.toString()); } return macBytes; }