List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
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 w w . j av a 2s .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:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] decrypt(byte[] secure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }/*from w ww. ja va2 s. c o m*/ testConfiguration(ctx); SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("decrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); mac.update(secure, 0, secure.length - macLenght); byte[] signedDigestHash = mac.doFinal(); boolean isMacEqual = true; for (int i = 0; i < signedDigestHash.length; i++) { if (signedDigestHash[i] != secure[secure.length - macLenght + i]) { isMacEqual = false; // MYFACES-2934 Must compare *ALL* bytes of the hash, // otherwise a side-channel timing attack is theorically possible // but with a very very low probability, because the // comparison time is too small to be measured compared to // the overall request time and in real life applications, // there are too many uncertainties involved. //break; } } if (!isMacEqual) { throw new ViewExpiredException(); } return cipher.doFinal(secure, 0, secure.length - macLenght); } catch (Exception e) { throw new FacesException(e); } }
From source file:com.cloud.servlet.ConsoleProxyServlet.java
public static String genAccessTicket(String host, String port, String sid, String tag, Date normalizedHashTime) { String params = "host=" + host + "&port=" + port + "&sid=" + sid + "&tag=" + tag; try {/*from w w w . j av a2 s.co m*/ Mac mac = Mac.getInstance("HmacSHA1"); long ts = normalizedHashTime.getTime(); ts = ts / 60000; // round up to 1 minute String secretKey = _ms.getHashKey(); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(params.getBytes()); mac.update(String.valueOf(ts).getBytes()); byte[] encryptedBytes = mac.doFinal(); return Base64.encodeBase64String(encryptedBytes); } catch (Exception e) { s_logger.error("Unexpected exception ", e); } return ""; }
From source file:com.amazon.dtasdk.v2.signature.Signer.java
protected final byte[] sign(byte[] dataBytes, byte[] keyBytes) throws SigningException { try {/*from ww w .jav a 2 s. c o m*/ Mac mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(keyBytes, ALGORITHM)); return mac.doFinal(dataBytes); } catch (NoSuchAlgorithmException nsae) { throw new SigningException(nsae); } catch (InvalidKeyException ike) { throw new SigningException(ike); } }
From source file:com.lili.ylpay.sdk.SecureUtil.java
/** * MAC/*from w ww .j a v a 2s. c om*/ * * @param inputByte * ? * @param inputkey * * @param inputmac * MAC * @return * @throws Exception */ public boolean checkmac(byte[] inputByte, byte[] inputkey, String inputmac) throws Exception { try { Mac mac = Mac.getInstance("HmacMD5"); SecretKey key = new SecretKeySpec(inputkey, "DES"); mac.init(key); byte[] macCode = mac.doFinal(inputByte); String strMacCode = this.byte2hex(macCode); return strMacCode.equals(inputmac); } catch (Exception ex) { throw ex; } }
From source file:acp.sdk.SecureUtil.java
/** * MAC//from ww w. j a va2 s .c o m * * @param inputByte * ? * @param inputkey * * @param inputmac * MAC * @return * @throws Exception */ public boolean checkmac(byte[] inputByte, byte[] inputkey, String inputmac) throws Exception { try { Mac mac = Mac.getInstance("HmacMD5"); SecretKey key = new SecretKeySpec(inputkey, "DES"); mac.init(key); byte[] macCode = mac.doFinal(inputByte); String strMacCode = this.byte2hex(macCode); if (strMacCode.equals(inputmac)) { return true; } else { return false; } } catch (Exception ex) { throw ex; } }
From source file:org.apache.qpid.systest.rest.SaslRestTest.java
private byte[] generateCramMD5HexClientResponse(String userName, String userPassword, byte[] challengeBytes) throws Exception { String macAlgorithm = "HmacMD5"; byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(userPassword.getBytes("UTF-8")); byte[] hexEncodedDigestedPasswordBytes = toHex(digestedPasswordBytes).getBytes("UTF-8"); Mac mac = Mac.getInstance(macAlgorithm); mac.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, macAlgorithm)); final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes); String responseAsString = userName + " " + toHex(messageAuthenticationCode); return responseAsString.getBytes(); }
From source file:be.cytomine.client.HttpClient.java
public static Header[] authorizeFromRETRIEVAL(String action, String urlFullStr, String contentType, String accept, String publicKey, String privateKey, String host) throws IOException { log.debug("authorize: action=" + action + ", url=" + urlFullStr + ", contentType=" + contentType + ",accept=" + accept); String url = urlFullStr.replace(host, ""); log.debug("authorize: url short=" + url); Header[] headers = new Header[3]; headers[0] = new BasicHeader("accept", accept); headers[1] = new BasicHeader("date", getActualDateStr()); String canonicalHeaders = action + "\n\n" + contentType + "\n" + headers[1].getValue() + "\n"; String messageToSign = canonicalHeaders + url; SecretKeySpec privateKeySign = new SecretKeySpec(privateKey.getBytes(), "HmacSHA1"); try {//from w w w . j ava2s .c o m Mac mac = Mac.getInstance("HmacSHA1"); mac.init(privateKeySign); byte[] rawHmac = mac.doFinal(new String(messageToSign.getBytes(), "UTF-8").getBytes()); //byte[] signatureBytes = Base64.encodeToByte(rawHmac,false); byte[] signatureBytes = org.apache.commons.codec.binary.Base64.encodeBase64(rawHmac, false); String authorization = "CYTOMINE " + publicKey + ":" + new String(signatureBytes); headers[2] = new BasicHeader("authorization", authorization); } catch (GeneralSecurityException e) { throw new IOException(e); } return headers; }
From source file:org.apache.qpid.systest.rest.SaslRestTest.java
private byte[] generateCramMD5ClientResponse(String userName, String userPassword, byte[] challengeBytes) throws Exception { String macAlgorithm = "HmacMD5"; Mac mac = Mac.getInstance(macAlgorithm); mac.init(new SecretKeySpec(userPassword.getBytes("UTF-8"), macAlgorithm)); final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes); String responseAsString = userName + " " + toHex(messageAuthenticationCode); return responseAsString.getBytes(); }
From source file:com.tcs.ebw.security.EBWSecurity.java
public void computeMac(String fileName) throws NoSuchAlgorithmException, InvalidKeyException , FileNotFoundException, IOException, NoSuchPaddingException { Mac mac = Mac.getInstance(EBWConstants.ENCRYPTION_MAC_ALGORITHM); mac.init(generateKeyForSymmetric()); FileInputStream fis = new FileInputStream(fileName); byte[] dataBytes = new byte[1024]; int nread = fis.read(dataBytes); while (nread > 0) { mac.update(dataBytes, 0, nread); nread = fis.read(dataBytes);/*from ww w .ja v a 2 s .com*/ } ; byte[] macbytes = mac.doFinal(); System.out.println("MAC(in hex):: " + ByteUtil.byteArrayToHex(macbytes)); //3e 17 56 a8 e7 19 4e cc da 87 69 ad 91 a0 b2 1a 83 3d 93 a4 }