List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
private String generateToken(String attachLocation) { if (StringUtils.isEmpty(attachment_key)) return ""; SecretKeySpec keySpec = new SecretKeySpec(attachment_key.getBytes(), "HmacMD5"); Mac mac; try {/*from w w w . ja v a2 s .com*/ mac = Mac.getInstance("HmacMD5"); mac.init(keySpec); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } String timestamp = "" + (getSystemTime() + serverTimeDelta); byte[] raw = mac.doFinal((timestamp + attachLocation).getBytes()); return new String(Hex.encodeHex(raw)) + ":" + timestamp; }
From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java
@Test public void verify_hmac_256_signature() throws Exception { String key = "key"; String data = "data"; SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKey); byte[] hmacData = mac.doFinal(data.getBytes("UTF-8")); assertThat(new String(Base64.encodeBase64URLSafe(hmacData)), equalTo(xoAuthAuthenticationManager.hmacSignAndEncode(data, key))); }
From source file:com.mastfrog.acteur.twitter.TwitterSign.java
String generateSignature(String data, AuthorizationResponse token) throws NoSuchAlgorithmException, InvalidKeyException { byte[] byteHMAC = null; Mac mac = Mac.getInstance(ALGORITHM); SecretKeySpec spec;/*from w w w .j av a 2 s . co m*/ if (token == null) { String signature = HttpParameter.encode(twitter_consumer_secret) + "&"; spec = new SecretKeySpec(signature.getBytes(), ALGORITHM); } else { String signature = HttpParameter.encode(twitter_consumer_secret) + "&" + HttpParameter.encode(token.accessTokenSecret); spec = new SecretKeySpec(signature.getBytes(), ALGORITHM); } mac.init(spec); byteHMAC = mac.doFinal(data.getBytes()); String sig = BASE64Encoder.encode(byteHMAC); return sig; }
From source file:net.spfbl.core.Core.java
private static long getCodeOTP(byte[] secret, long timeIndex) { try {/*from w w w . j av a 2s.com*/ SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1"); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(timeIndex); byte[] timeBytes = buffer.array(); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(timeBytes); int offset = hash[19] & 0xf; long truncatedHash = hash[offset] & 0x7f; for (int i = 1; i < 4; i++) { truncatedHash <<= 8; truncatedHash |= hash[offset + i] & 0xff; } return (truncatedHash %= 1000000); } catch (Exception ex) { return 0; } }
From source file:com.cloud.api.ApiServer.java
public boolean verifyRequest(Map<String, Object[]> requestParameters, Long userId) throws ServerApiException { try {//from w w w . java 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.emc.esu.api.rest.AbstractEsuRestApi.java
public String sign(byte[] input) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1"); mac.init(key); byte[] hashData = mac.doFinal(input); // Encode the hash in Base64. return new String(Base64.encodeBase64(hashData), "UTF-8"); }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method, @Nonnull Map<String, String> queryParams) throws CloudException, InternalException { fetchKeys();/* w w w . j a v a 2 s. co m*/ ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new AzureConfigException("No context was specified for this request"); } Header h = method.getFirstHeader("content-type"); String contentType = (h == null ? null : h.getValue()); if (contentType == null) { contentType = ""; } StringBuilder stringToSign = new StringBuilder(); stringToSign.append(method.getMethod().toUpperCase()).append("\n"); stringToSign.append("\n"); // content-md5 stringToSign.append(contentType).append("\n"); stringToSign.append(method.getFirstHeader("date").getValue()).append("\n"); Header[] headers = method.getAllHeaders(); TreeSet<String> keys = new TreeSet<String>(); for (Header header : headers) { if (header.getName().startsWith(Header_Prefix_MS)) { keys.add(header.getName().toLowerCase()); } } for (String key : keys) { Header header = method.getFirstHeader(key); if (header != null) { Header[] all = method.getHeaders(key); stringToSign.append(key.toLowerCase().trim()).append(":"); if (all != null && all.length > 0) { for (Header current : all) { String v = (current.getValue() != null ? current.getValue() : ""); stringToSign.append(v.trim().replaceAll("\n", " ")).append(","); } } stringToSign.deleteCharAt(stringToSign.lastIndexOf(",")); } else { stringToSign.append(key.toLowerCase().trim()).append(":"); } stringToSign.append("\n"); } stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath()); keys.clear(); for (String key : queryParams.keySet()) { if (key.equalsIgnoreCase("comp")) { key = key.toLowerCase(); keys.add(key); } } if (!keys.isEmpty()) { stringToSign.append("?"); for (String key : keys) { String value = queryParams.get(key); if (value == null) { value = ""; } stringToSign.append(key).append("=").append(value).append("&"); } stringToSign.deleteCharAt(stringToSign.lastIndexOf("&")); } try { if (logger.isDebugEnabled()) { logger.debug("BEGIN STRING TO SIGN"); logger.debug(stringToSign.toString()); logger.debug("END STRING TO SIGN"); } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256")); String signature = new String( Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8")))); if (logger.isDebugEnabled()) { logger.debug("signature=" + signature); } return signature; } catch (UnsupportedEncodingException e) { logger.error("UTF-8 not supported: " + e.getMessage()); throw new InternalException(e); } catch (NoSuchAlgorithmException e) { logger.error("No such algorithm: " + e.getMessage()); throw new InternalException(e); } catch (InvalidKeyException e) { logger.error("Invalid key: " + e.getMessage()); throw new InternalException(e); } }
From source file:com.cloud.test.stress.TestClientWithAPI.java
public static String signRequest(String request, String key) { try {/*from www. j a va 2s. com*/ 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.gaul.s3proxy.S3ProxyHandler.java
private static byte[] signMessage(byte[] data, byte[] key, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException { Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return mac.doFinal(data); }
From source file:com.google.acre.script.HostEnv.java
@JSFunction public String hmac(String algorithm, String key, String data, boolean to_hex) { try {/*from w ww . j a v a 2s . c o m*/ SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(signingKey); if (to_hex) { return new String(Hex.encodeHex(mac.doFinal(data.getBytes()))); } else { return new String(Base64.encodeBase64(mac.doFinal(data.getBytes()))); } } catch (InvalidKeyException e) { throw new JSConvertableException("Invalid key: " + key).newJSException(this); } catch (NoSuchAlgorithmException e) { throw new JSConvertableException("Unable to load algoritm: " + algorithm).newJSException(this); } }