List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal() throws IllegalStateException
From source file:com.playhaven.android.req.PlayHavenRequest.java
protected String createHmac(SharedPreferences pref, String content, boolean stripEquals) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { String secret = getString(pref, Secret); SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC); Mac hmac = Mac.getInstance(HMAC); hmac.init(key);//from w ww.j a va 2 s .c o m hmac.update(content.getBytes(UTF8)); byte[] bytes = hmac.doFinal(); String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim(); if (stripEquals) derived = derived.replaceAll("=", ""); return derived; }
From source file:be.fedict.eid.idp.webapp.ProtocolExitServlet.java
/** * Optionally encrypt the user ID//www .j a va2 s . c om * * @param userId * user ID to encrypt ( or not ) * @param rp * rp, can be null * @return (encrypted) user ID */ private String getUniqueId(String userId, RPEntity rp) { String uniqueId = userId; byte[] hmacSecret = getIdentifierSecret(rp); if (null != hmacSecret) { Mac mac; try { mac = CryptoUtil.getMac(hmacSecret); } catch (InvalidKeyException e) { throw new RuntimeException("Invalid key", e); } mac.update(uniqueId.getBytes()); byte[] resultHMac = mac.doFinal(); uniqueId = new String(Hex.encodeHex(resultHMac)).toUpperCase(); } return uniqueId; }
From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentials.java
private String computeMacSha(String canonicalizedString) { Mac mac; try {/*from w w w.j a v a2 s . com*/ if (getKey() == null) { throw new StorageClientException(StorageErrorCode.AccountNotFound, "The Windows Azure storage account credentials contains invalid values.", HttpStatusConstant.DEFAULT_STATUS, null, null); } mac = Mac.getInstance(HMACSHA256); mac.init(new SecretKeySpec(getKey(), mac.getAlgorithm())); byte[] dataToMAC = canonicalizedString.getBytes(UTF8_CHARSET); mac.update(dataToMAC); byte[] result = mac.doFinal(); return Base64.encode(result); } catch (NoSuchAlgorithmException e) { Logger.error("NoSuchAlgorithmException", e); } catch (InvalidKeyException e) { Logger.error("InvalidKeyException", e); } catch (UnsupportedEncodingException e) { Logger.error("UnsupportedEncodingException", e); } return null; }
From source file:com.cloud.servlet.ConsoleProxyServlet.java
private boolean verifyRequest(Map<String, Object[]> requestParameters) { try {//from w w w .j a v a2 s .c om String apiKey = null; String secretKey = null; String signature = null; String unsignedRequest = null; // - build a request string with sorted params, make sure it's all lowercase // - sign the request, verify the signature is the same List<String> parameterNames = new ArrayList<String>(); for (Object paramNameObj : requestParameters.keySet()) { parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] String paramValue = ((String[]) requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; } else { if ("apikey".equalsIgnoreCase(paramName)) { apiKey = paramValue; } if (unsignedRequest == null) { unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } else { unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } } } // if api/secret key are passed to the parameters if ((signature == null) || (apiKey == null)) { if (s_logger.isDebugEnabled()) { s_logger.debug( "expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); } return false; // no signature, bad request } Transaction txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); User user = null; // verify there is a user with this api key Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey); if (userAcctPair == null) { s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } user = userAcctPair.first(); Account account = userAcctPair.second(); if (!user.getState().equals(Account.State.enabled) || !account.getState().equals(Account.State.enabled)) { s_logger.debug("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState()); return false; } // verify secret key exists secretKey = user.getSecretKey(); if (secretKey == null) { s_logger.debug( "User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername()); return false; } unsignedRequest = unsignedRequest.toLowerCase(); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(unsignedRequest.getBytes()); byte[] encryptedBytes = mac.doFinal(); String computedSignature = Base64.encodeBase64URLSafeString(encryptedBytes); boolean equalSig = signature.equals(computedSignature); if (!equalSig) { s_logger.debug("User signature: " + signature + " is not equaled to computed signature: " + computedSignature); } if (equalSig) { requestParameters.put("userid", new Object[] { String.valueOf(user.getId()) }); requestParameters.put("account", new Object[] { account.getAccountName() }); requestParameters.put("accountobj", new Object[] { account }); } return equalSig; } catch (Exception ex) { s_logger.error("unable to verifty request signature", ex); } return false; }
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 w w w . j a va2 s . co m*/ } ; 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 }
From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.SignatureGenerator.java
public String getSignature(String secretKey) { Mac mac; try {//from w w w . j a v a 2 s .co m mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(secretKey.getBytes(), ALGORITHM)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } mac.update(method.getBytes()); mac.update((byte) '\n'); mac.update(host.getBytes()); mac.update((byte) '\n'); mac.update(path.getBytes()); mac.update((byte) '\n'); boolean addAmpersand = false; for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { byte[] nameBytes = encodeString(entry.getKey()); List<String> values = entry.getValue(); Collections.sort(values); for (String value : values) { if (addAmpersand) { mac.update((byte) '&'); } else { addAmpersand = true; } byte[] valueBytes = encodeString(value); mac.update(nameBytes); mac.update((byte) '='); mac.update(valueBytes); } } byte[] digest = mac.doFinal(); return new String(Base64.encodeBase64(digest)); }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
@Override public boolean authenticateContent(SeekableByteChannel encryptedFile) throws IOException { // init mac://from w w w . j a va 2 s.c om final Mac calculatedMac = this.hmacSha256(hMacMasterKey); // read stored mac: encryptedFile.position(16); final ByteBuffer storedMac = ByteBuffer.allocate(calculatedMac.getMacLength()); final int numMacBytesRead = encryptedFile.read(storedMac); // check validity of header: if (numMacBytesRead != calculatedMac.getMacLength()) { throw new IOException("Failed to read file header."); } // read all encrypted data and calculate mac: encryptedFile.position(64); final InputStream in = new SeekableByteChannelInputStream(encryptedFile); final InputStream macIn = new MacInputStream(in, calculatedMac); IOUtils.copyLarge(macIn, new NullOutputStream()); // compare (in constant time): return MessageDigest.isEqual(storedMac.array(), calculatedMac.doFinal()); }
From source file:com.cloud.api.ApiServer.java
public boolean verifyRequest(Map<String, Object[]> requestParameters, Long userId) throws ServerApiException { try {//from ww w.j a v a 2 s. c o m String apiKey = null; String secretKey = null; String signature = null; String unsignedRequest = null; String[] command = (String[]) requestParameters.get("command"); if (command == null) { s_logger.info("missing command, ignoring request..."); return false; } String commandName = command[0]; // if userId not null, that mean that user is logged in if (userId != null) { Long accountId = ApiDBUtils.findUserById(userId).getAccountId(); Account userAccount = _accountMgr.getAccount(accountId); short accountType = userAccount.getType(); if (!isCommandAvailable(accountType, commandName)) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); } return true; } else { // check against every available command to see if the command exists or not if (!isCommandAvailable(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); } } // - build a request string with sorted params, make sure it's all lowercase // - sign the request, verify the signature is the same List<String> parameterNames = new ArrayList<String>(); for (Object paramNameObj : requestParameters.keySet()) { parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); String signatureVersion = null; String expires = null; for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] String paramValue = ((String[]) requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; } else { if ("apikey".equalsIgnoreCase(paramName)) { apiKey = paramValue; } else if ("signatureversion".equalsIgnoreCase(paramName)) { signatureVersion = paramValue; } else if ("expires".equalsIgnoreCase(paramName)) { expires = paramValue; } if (unsignedRequest == null) { unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } else { unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } } } // if api/secret key are passed to the parameters if ((signature == null) || (apiKey == null)) { if (s_logger.isDebugEnabled()) { s_logger.info( "expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); } return false; // no signature, bad request } Date expiresTS = null; if ("3".equals(signatureVersion)) { // New signature authentication. Check for expire parameter and its validity if (expires == null) { s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); return false; } synchronized (_dateFormat) { try { expiresTS = _dateFormat.parse(expires); } catch (ParseException pe) { s_logger.info("Incorrect date format for Expires parameter", pe); return false; } } Date now = new Date(System.currentTimeMillis()); if (expiresTS.before(now)) { s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey); return false; } } Transaction txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); User user = null; // verify there is a user with this api key Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey); if (userAcctPair == null) { s_logger.info("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } user = userAcctPair.first(); Account account = userAcctPair.second(); if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) { s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState()); return false; } UserContext.updateContext(user.getId(), account, null); if (!isCommandAvailable(account.getType(), commandName)) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist"); } // verify secret key exists secretKey = user.getSecretKey(); if (secretKey == null) { s_logger.info( "User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername()); return false; } unsignedRequest = unsignedRequest.toLowerCase(); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(unsignedRequest.getBytes()); byte[] encryptedBytes = mac.doFinal(); String computedSignature = Base64.encodeBase64String(encryptedBytes); boolean equalSig = signature.equals(computedSignature); if (!equalSig) { s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature); } return equalSig; } catch (Exception ex) { if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) { throw (ServerApiException) ex; } s_logger.error("unable to verifty request signature", ex); } return false; }
From source file:com.cloud.test.stress.TestClientWithAPI.java
public static String signRequest(String request, String key) { try {//from w ww . ja va2 s .c o m Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); return org.apache.commons.codec.binary.Base64.encodeBase64String(encryptedBytes); } catch (Exception ex) { s_logger.error("unable to sign request", ex); } return null; }
From source file:org.androdyne.StacktraceUploader.java
/** * Given the NameValuePairs forming a stacktrace submission request, creates a * signature over the parameters that the API should recognize. **//*w w w . j a v a2s .c om*/ private String createSignature(List<NameValuePair> params) { // First, sort the parameter keys. That'll help later. List<String> sortedKeys = new LinkedList<String>(); for (NameValuePair pair : params) { sortedKeys.add(pair.getName()); } Collections.sort(sortedKeys, String.CASE_INSENSITIVE_ORDER); // Create signature. Mac hmac = null; try { hmac = Mac.getInstance("HmacSHA1"); hmac.init(new SecretKeySpec(mAPISecret.getBytes(), "HmacSHA1")); } catch (NoSuchAlgorithmException ex) { android.util.Log.e(LTAG, "No HmacSHA1 available on this phone."); return null; } catch (InvalidKeyException ex) { android.util.Log.e(LTAG, "Invalid secret; shouldn't be possible."); return null; } final int size = sortedKeys.size(); for (int i = 0; i < size; ++i) { String key = sortedKeys.get(i); for (NameValuePair pair : params) { if (!key.equals(pair.getName())) { continue; } // This pair is next! try { hmac.update(String.format("%s=%s", key, URLEncoder.encode(pair.getValue(), "utf8")).getBytes()); } catch (java.io.UnsupportedEncodingException ex) { android.util.Log.e(LTAG, "URLEncoder reports 'utf8' is an unsupported encoding..."); return null; } if (i < size - 1) { hmac.update("&".getBytes()); } } } String signature = new BigInteger(1, hmac.doFinal()).toString(16); // android.util.Log.d(LTAG, "signature: " + signature); return signature; }