List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString
public static String encodeBase64URLSafeString(final byte[] binaryData)
From source file:org.saadahmed.snowcrystal.SnowCrystal.java
public static String sha384Base64UrlSafe() { return Base64.encodeBase64URLSafeString(DigestUtils.sha384(SnowCrystal.newId().unwrap())); }
From source file:org.saadahmed.snowcrystal.SnowCrystal.java
public static String sha512Base64URLSafe() { return Base64.encodeBase64URLSafeString(DigestUtils.sha512(SnowCrystal.newId().unwrap())); }
From source file:org.sakaiproject.nakamura.api.lite.StorageClientUtils.java
public static String encode(byte[] hash) { return Base64.encodeBase64URLSafeString(hash); }
From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java
/** * @param request/*w ww. jav a 2 s . co m*/ * @param urlPath * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws IllegalStateException * @throws UnsupportedEncodingException */ private String getTransferUrl(HttpServletRequest request, String urlPath) { String trustedHostHeader = buildTrustedHostHeader(request); if (trustedHostHeader == null || !applicationContentRedirects.containsKey(trustedHostHeader)) { LOGGER.warn("No Content Host found for {} ", request.getRequestURL()); throw new IllegalArgumentException("No Content Host foudn for request, cant transfer "); } String redirectUrl = applicationContentRedirects.get(trustedHostHeader) + urlPath; // only transfer authN from a trusted safe host if (isSafeHost(request)) { String userId = request.getRemoteUser(); if (userId != null && !User.ANON_USER.equals(userId)) { try { long ts = System.currentTimeMillis(); int keyIndex = (int) (ts - ((ts / 10) * 10)); Mac m = Mac.getInstance(HMAC_SHA512); m.init(transferKeys[keyIndex]); String message = createMessage(redirectUrl, userId, String.valueOf(ts)); m.update(message.getBytes("UTF-8")); String hmac = Base64.encodeBase64URLSafeString(m.doFinal()); hmac = Base64.encodeBase64URLSafeString((hmac + ";" + userId + ";" + ts).getBytes("UTF-8")); String spacer = "?"; if (redirectUrl.indexOf('?') > 0) { spacer = "&"; } redirectUrl = redirectUrl + spacer + HMAC_PARAM + "=" + hmac; LOGGER.debug("Message was [{}] ", message); LOGGER.debug("Key was [{}] [{}] ", keyIndex, transferKeys[keyIndex]); LOGGER.debug("Transfer URL created as [{}] ", redirectUrl); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } } } return redirectUrl; }
From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java
public String getTransferUserId(HttpServletRequest request) { // only ever get a user ID in this way on a non trusted safe host. if (disableProtectionForDevMode) { LOGGER.warn("XSS Protection is disabled [getTransferUserId]"); return null; }/*from w w w. j av a 2 s.c om*/ // the host must not be safe to decode the user transfer UserID, and the method must be a GET or HEAD String method = request.getMethod(); if (!isSafeHost(request) && ("GET".equals(method) || "HEAD".equals(method))) { String hmac = request.getParameter(HMAC_PARAM); if (hmac != null) { try { hmac = new String(Base64.decodeBase64(hmac.getBytes("UTF-8")), "UTF-8"); String[] parts = StringUtils.split(hmac, ';'); String requestUrl = request.getRequestURL().append("?").append(request.getQueryString()) .toString(); LOGGER.debug("Checking requestUrl [{}", requestUrl); int i = requestUrl.indexOf("&" + HMAC_PARAM); if (i < 0) { i = requestUrl.indexOf("?" + HMAC_PARAM); } String finalUrl = requestUrl.substring(0, i); String requestHmac = parts[0]; String requestUserId = parts[1]; String requestTs = parts[2]; String message = createMessage(finalUrl, requestUserId, requestTs); long requestTsL = Long.parseLong(requestTs); if (Math.abs(System.currentTimeMillis() - requestTsL) < 60000L) { int keyIndex = (int) (requestTsL - ((requestTsL / 10) * 10)); Mac m = Mac.getInstance(HMAC_SHA512); m.init(transferKeys[keyIndex]); m.update(message.getBytes("UTF-8")); String testHmac = Base64.encodeBase64URLSafeString(m.doFinal()); if (testHmac.equals(requestHmac)) { LOGGER.debug("Successfully extracted requestUserId {} from HMAC", requestUserId); return requestUserId; } else { LOGGER.debug("Message was [{}] ", message); LOGGER.debug("Key was [{}] [{}] ", keyIndex, transferKeys[keyIndex]); LOGGER.debug("Hmac did not validate testHmac was [{}], requestHmac [{}] ", testHmac, requestHmac); } } else { LOGGER.debug("Hmac has expired, older than 60s, hmac message was {} ", message); } } catch (Exception e) { LOGGER.warn(e.getMessage()); LOGGER.debug(e.getMessage(), e); } } } else { LOGGER.debug("Request is to a safe host, wont look for a transfer of trust to this host. {} ", request.getRequestURL().toString()); } return null; }
From source file:org.sakaiproject.nakamura.lite.accesscontrol.AccessControlManagerImpl.java
public void setAcl(String objectType, String objectPath, AclModification[] aclModifications) throws StorageClientException, AccessDeniedException { checkOpen();//w w w .j a v a 2 s . c o m check(objectType, objectPath, Permissions.CAN_WRITE_ACL); check(objectType, objectPath, Permissions.CAN_READ_ACL); String key = this.getAclKey(objectType, objectPath); Map<String, Object> currentAcl = getCached(keySpace, aclColumnFamily, key); // every ACL gets a secret key, which avoids doing it later with a special call Map<String, Object> modifications = Maps.newLinkedHashMap(); if (!currentAcl.containsKey(_SECRET_KEY)) { byte[] secretKeySeed = new byte[20]; secureRandom.nextBytes(secretKeySeed); MessageDigest md; try { md = MessageDigest.getInstance("SHA1"); modifications.put(_SECRET_KEY, Base64.encodeBase64URLSafeString(md.digest(secretKeySeed))); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } } if (!currentAcl.containsKey(_KEY)) { modifications.put(_KEY, key); modifications.put(_OBJECT_TYPE, objectType); // this is here to make data migration possible in the future modifications.put(_PATH, objectPath); // same } for (AclModification m : aclModifications) { String name = m.getAceKey(); if (READ_ONLY_PROPERTIES.contains(name)) { continue; } if (m.isRemove()) { modifications.put(name, null); } else { int originalbitmap = getBitMap(name, modifications, currentAcl); int modifiedbitmap = m.modify(originalbitmap); LOGGER.debug("Adding Modification {} {} ", name, modifiedbitmap); modifications.put(name, modifiedbitmap); // KERN-1515 // We need to modify the opposite key to apply the // reverse of the change we just made. Otherwise, // you can end up with ACLs with contradictions, like: // anonymous@g=1, anonymous@d=1 if (containsKey(inverseKeyOf(name), modifications, currentAcl)) { // XOR gives us a mask of only the bits that changed int difference = originalbitmap ^ modifiedbitmap; int otherbitmap = toInt(getBitMap(inverseKeyOf(name), modifications, currentAcl)); // Zero out the bits that have been modified // // KERN-1887: This was originally toggling the modified bits // using: "otherbitmap ^ difference", but this would // incorrectly grant permissions in some cases (see JIRA // issue). To avoid inconsistencies between grant and deny // lists, setting a bit in one list should unset the // corresponding bit in the other. int modifiedotherbitmap = otherbitmap & ~difference; if (otherbitmap != modifiedotherbitmap) { // We made a change. Record our modification. modifications.put(inverseKeyOf(name), modifiedotherbitmap); } } } } LOGGER.debug("Updating ACL {} {} ", key, modifications); putCached(keySpace, aclColumnFamily, key, modifications, (currentAcl == null || currentAcl.size() == 0)); storeListener.onUpdate(objectType, objectPath, getCurrentUserId(), false, null, "op:acl"); }
From source file:org.sakaiproject.nakamura.messagebucket.UntrustedMessageBucketServiceImpl.java
public String getToken(String userId, String context) throws MessageBucketException { try {/*from ww w .j a v a 2s. c o m*/ String timeStamp = Long.toHexString(System.currentTimeMillis()); String hmac = Signature.calculateRFC2104HMAC(userId + ";" + timeStamp + ";" + context, sharedSecret); String token = userId + ";" + timeStamp + ";" + context + ";" + hmac; return Base64.encodeBase64URLSafeString(token.getBytes("UTF8")); } catch (SignatureException e) { throw new MessageBucketException(e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new MessageBucketException(e.getMessage(), e); } }
From source file:org.sakaiproject.nakamura.personal.JCRPersonalTrackingStore.java
/** * {@inheritDoc}//from w w w. j a v a2 s . co m * * @see org.sakaiproject.nakamura.api.personal.PersonalTrackingStore#recordActivity(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.util.Date) */ public void recordActivity(String resourceId, String resourceType, String activityType, String userId, Calendar timestamp) { Session session = null; try { session = slingRepository.loginAdministrative(null); Node trackingNode = JcrUtils.deepGetOrCreateNode(session, "/activity/" + resourceType + "/" + resourceId); if (!trackingNode.hasProperty("count")) { trackingNode.setProperty("count", 0); } if (!trackingNode.hasProperty("sling:resourceType")) { trackingNode.setProperty("sling:resourceType", "sakai/resource-activity"); } String generatedNodeName = Base64.encodeBase64URLSafeString(asShorterByteArray(UUID.randomUUID())); Node activityNode = trackingNode.addNode(generatedNodeName); BigDecimal activityCount = trackingNode.getProperty("count").getDecimal(); activityNode.setProperty("sling:resourceType", "sakai/resource-update"); trackingNode.setProperty("count", activityCount.add(BigDecimal.ONE)); activityNode.setProperty("resourceId", resourceId); activityNode.setProperty("resourcetype", resourceType); activityNode.setProperty("activitytype", activityType); activityNode.setProperty("timestamp", timestamp); activityNode.setProperty("userid", userId); if (session.hasPendingChanges()) { session.save(); } } catch (RepositoryException e) { e.printStackTrace(); } finally { if (session != null) { session.logout(); } } }
From source file:org.sakaiproject.nakamura.personal.LitePersonalTrackingStore.java
/** * {@inheritDoc}/*from ww w .j ava 2 s . c o m*/ * * @see org.sakaiproject.nakamura.api.personal.PersonalTrackingStore#recordActivity(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.util.Date) */ public void recordActivity(String resourceId, String resourceType, String activityType, String userId, Calendar timestamp) { Session session = null; try { session = repository.loginAdministrative(); final ContentManager cm = session.getContentManager(); final String trackingNodePath = "/activity/" + resourceType + "/" + resourceId; Content trackingNode = cm.get(trackingNodePath); if (trackingNode == null) { trackingNode = new Content(trackingNodePath, new HashMap<String, Object>()); } if (!trackingNode.hasProperty("count")) { trackingNode.setProperty("count", BigDecimal.ZERO); } if (!trackingNode.hasProperty("sling:resourceType")) { trackingNode.setProperty("sling:resourceType", "sakai/resource-activity"); } final String generatedNodeName = Base64 .encodeBase64URLSafeString(asShorterByteArray(UUID.randomUUID())); final String activityNodePath = trackingNodePath + "/" + generatedNodeName; Content activityNode = null; if (cm.exists(activityNodePath)) { activityNode = cm.get(activityNodePath); } else { activityNode = new Content(activityNodePath, new HashMap<String, Object>()); } BigDecimal activityCount = (BigDecimal) trackingNode.getProperty("count"); activityNode.setProperty("sling:resourceType", "sakai/resource-update"); trackingNode.setProperty("count", activityCount.add(BigDecimal.ONE)); activityNode.setProperty("resourceId", resourceId); activityNode.setProperty("resourcetype", resourceType); activityNode.setProperty("activitytype", activityType); activityNode.setProperty("timestamp", timestamp); activityNode.setProperty("userid", userId); cm.update(activityNode); cm.update(trackingNode); } catch (AccessDeniedException e) { LOG.error(e.getLocalizedMessage(), e); } catch (StorageClientException e) { LOG.error(e.getLocalizedMessage(), e); } finally { if (session != null) { try { session.logout(); } catch (ClientPoolException e) { LOG.error(e.getLocalizedMessage(), e); throw new IllegalStateException(e); } } } }
From source file:org.sikuliserver.test.callServlet.java
public static void main(String[] args) { String url = "http://localhost:5556/extra/ExecuteSikuliAction"; URL obj;//from w ww. j a v a2 s. c om try { obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; URL urlPicture = new URL("file:///C:/Users/bcivel/Documents/Selenium.sikuli/1441615900282.png"); InputStream istream = urlPicture.openStream(); byte[] bytes = IOUtils.toByteArray(istream); String imageDataString = Base64.encodeBase64URLSafeString(bytes); JSONObject object = new JSONObject(); object.put("action", "click"); object.put("picture", imageDataString); // Send post request con.setDoOutput(true); //DataOutputStream wr = new DataOutputStream(con.getOutputStream()); PrintStream os = new PrintStream(con.getOutputStream()); // wr.writeBytes(object.toString()); // wr.writeBytes("|ENDS|"); // wr.flush(); // wr.close(); os.println(object.toString()); os.println("|ENDS|"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + object.toString()); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } catch (MalformedURLException ex) { Logger.getLogger(callServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(callServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(callServlet.class.getName()).log(Level.SEVERE, null, ex); } }