List of usage examples for org.apache.commons.codec.digest DigestUtils sha1Hex
public static String sha1Hex(String data)
From source file:co.cask.hydrator.plugin.HasherTest.java
@Test public void testHasherSHA1() throws Exception { Transform<StructuredRecord, StructuredRecord> transform = new Hasher(new Hasher.Config("SHA1", "a,b,e")); transform.initialize(null);//from www. j ava2 s . co m MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); transform.transform(StructuredRecord.builder(INPUT).set("a", "Field A").set("b", "Field B") .set("c", "Field C").set("d", 4).set("e", "Field E").build(), emitter); ; Assert.assertEquals(5, emitter.getEmitted().get(0).getSchema().getFields().size()); Assert.assertEquals(DigestUtils.sha1Hex("Field A"), emitter.getEmitted().get(0).get("a")); Assert.assertEquals(DigestUtils.sha1Hex("Field B"), emitter.getEmitted().get(0).get("b")); Assert.assertEquals("Field C", emitter.getEmitted().get(0).get("c")); Assert.assertEquals(4, emitter.getEmitted().get(0).get("d")); Assert.assertEquals(DigestUtils.sha1Hex("Field E"), emitter.getEmitted().get(0).get("e")); }
From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java
/** * The method is synchronized since the caching seems to have issues upon mult-threaded caching * @param overwrite if true, it would overwrite the values on cache *//*from www. j a v a 2 s . c om*/ public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception { String viewsConnected = Arrays.toString(viewsToAdd); String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", ""); ConcurrentMap<String, byte[]> concurrentMap = (db != null) ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen() : null; String key = DigestUtils.sha1Hex(str + views); if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) { byte[] taByte = concurrentMap.get(key); return SerializationHelper.deserializeTextAnnotationFromBytes(taByte); } else { URL obj = new URL(url + ":" + port + "/annotate"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); con.setUseCaches(false); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views); wr.flush(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(reader); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); reader.close(); wr.close(); con.disconnect(); TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString()); if (concurrentMap != null) { concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta)); this.db.commit(); } return ta; } }
From source file:com.jiusit.onePurchase.pay.Pay.java
/** * package, ??//from w w w . ja v a 2s. com * @param params * @param paternerKey * @return * @throws UnsupportedEncodingException */ public static String setJsapiSign(Map<String, String> params) throws UnsupportedEncodingException { String string1 = createSign(params, false); String signValue = DigestUtils.sha1Hex(string1); return signValue; }
From source file:com.veterinaria.jsf.controllers.ClienteController.java
public String addCliente() { try {/*from ww w. j a v a2s .c o m*/ clienteActual.setPassword(DigestUtils.sha1Hex(password)); clienteActual.setFechaCreacionCliente(new Date()); clienteActual.setEstado(true); getClienteFacade().create(clienteActual); addSuccesMessage("CLIENTE CREADO", "Cliente Creado Exitosamente."); recargarLista(); FacesContext.getCurrentInstance().getExternalContext().redirect("clientesList.xhtml"); return "/faces/clientes/clientesList"; } catch (IOException e) { addErrorMessage("Error closing resource " + e.getClass().getName(), "Message: " + e.getMessage()); return null; } }
From source file:com.openthinks.webscheduler.service.WebSecurityService.java
public Cookie createRememberMeCookie() { Cookie cookie = new Cookie(StaticDict.COOKIE_REMEMBER_ME, DigestUtils.sha1Hex(StaticUtils.UUID())); cookie.setMaxAge(StaticDict.COOKIE_REMEMBER_ME_EXPIRE_TIME); cookie.setPath(StaticUtils.getRootContext()); return cookie; }
From source file:com.lr.backer.controller.Pay.java
/** * ??//from w w w . j a va 2 s . c om * @param timestamp * @param noncestr * @param openid * @param issubscribe * @param appsignature * @return * @throws UnsupportedEncodingException */ public static boolean verifySign(long timestamp, String noncestr, String openid, int issubscribe, String appsignature) throws UnsupportedEncodingException { Map<String, String> paras = new HashMap<String, String>(); paras.put("appid", ConfKit.get("AppId")); paras.put("appkey", ConfKit.get("paySignKey")); paras.put("timestamp", String.valueOf(timestamp)); paras.put("noncestr", noncestr); paras.put("openid", openid); paras.put("issubscribe", String.valueOf(issubscribe)); // appid?appkey?productid?timestamp?noncestr?openid?issubscribe String string1 = createSign(paras, false); String paySign = DigestUtils.sha1Hex(string1); return paySign.equalsIgnoreCase(appsignature); }
From source file:edu.si.services.beans.edansidora.EdanApiBean.java
/** * Setting the required http request headers for EDAN Authentication * (See <a href="http://edandoc.si.edu/authentication">http://edandoc.si.edu/authentication</a> for more information) * * @param edanQuery the EDAN Query string *///w ww .j a v a 2 s . c om public void setEdanAuth(String edanQuery) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-1"); nonce = UUID.randomUUID().toString().replace("-", ""); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdfDate = df.format(new Date()); LOG.debug("setEdanAuth edanParams = {}", edanQuery); authContent = Base64Utility.encode( DigestUtils.sha1Hex(nonce + "\n" + edanQuery + "\n" + sdfDate + "\n" + edan_key).getBytes("UTF-8")); }
From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java
/** * Maps POM requests simulating a Maven 2 directory structure. * @throws IOException/*from w w w. ja va 2 s.com*/ */ @GET @Path("{groupIdPath:[a-zA-Z0-9\\-\\_]+(/[a-zA-Z0-9\\-\\_]+)*}" + "/{artifactId:[a-zA-Z0-9\\-\\_\\.]+}" + "/{version:\\d+(\\.\\d+)*}" + "/{artifactIdFilename:[a-zA-Z0-9\\-\\_\\.]+}" + "-{versionFilename:\\d+(\\.\\d+)*}" + ".{fileExtension:pom(\\.sha1)?}") @Timed public Response getPom(@PathParam("groupIdPath") String groupIdPath, @PathParam("artifactId") String artifactId, @PathParam("version") String version, @PathParam("artifactIdFilename") String artifactIdFilename, @PathParam("versionFilename") String versionFilename, @PathParam("fileExtension") String fileExtension) throws IOException { String groupId = mapGroupId(groupIdPath); if (!validateBasicParams(groupId, artifactId, version, artifactIdFilename, versionFilename)) { return Response.status(Response.Status.NOT_FOUND).build(); } ArtifactType artifactType = getArtifactType(artifactId); // validate that version exists String url = getPomValidateUrl(artifactType, version); log.info("Validate file: {}", url); HttpHead get = new HttpHead(url); HttpResponse response = httpClient.execute(get); try { if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { return Response.status(Response.Status.NOT_FOUND).build(); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } String xml = PomBuilder.build(groupId, artifactId, version, "pom"); if (StringUtils.equals(fileExtension, "pom")) { return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } if (StringUtils.equals(fileExtension, "pom.sha1")) { return Response.ok(DigestUtils.sha1Hex(xml)).type(MediaType.TEXT_PLAIN).build(); } return Response.status(Response.Status.NOT_FOUND).build(); }
From source file:com.eriwen.gradle.Digest.java
private String digest(final File file, final DigestAlgorithm algorithm) throws IOException { final byte[] contentBytes = Files.readAllBytes(file.toPath()); final String checksum; switch (algorithm) { case MD5:/*from w ww. j a va2 s .c o m*/ checksum = DigestUtils.md5Hex(contentBytes); break; case SHA1: checksum = DigestUtils.sha1Hex(contentBytes); break; case SHA256: checksum = DigestUtils.sha256Hex(contentBytes); break; case SHA512: checksum = DigestUtils.sha512Hex(contentBytes); break; default: throw new IllegalArgumentException("Cannot use unknown digest algorithm " + algorithm.toString()); } return checksum; }
From source file:com.wordpress.metaphorm.authProxy.hook.AuthProxyServletFilter.java
private OAuthState getOAuthState(HttpServletRequest servletReq, HttpServletResponse servletResp) throws ExpiredStateException { String userToken = servletReq.getHeader("userToken"); if (userToken == null) { // If not provided via XForms <submission/> header ... // ... then a web browser is client so use the servlet session ID hashed (to protect it) userToken = DigestUtils.sha1Hex(servletReq.getSession().getId()); }/*from w w w .j a va 2s.c om*/ OAuthState oAuthState = OAuthStateManager.getOAuthState(userToken); if (oAuthState == null) { // If first interaction ... // userToken was generated by the portlet filter, now needs an OAuthState if (userToken.startsWith("PORTLET:")) { _log.debug("Received userToken back from portlet: " + userToken); UserToken userTokenObj = UserToken.parseFromString(userToken); if (!userTokenObj.isUntampedWith()) { _log.debug("Looks like the userToken has been tampered with!"); throw new ExpiredStateException(); } if (userTokenObj.userId > 0) { ServiceContext serviceContext = new ServiceContext(); serviceContext.setCompanyId(userTokenObj.companyId); serviceContext.setScopeGroupId(userTokenObj.scopeGroupId); serviceContext.setUserId(userTokenObj.userId); PortalAuthedSessionOAuthStateImpl oAuthStateImpl = new PortalAuthedSessionOAuthStateImpl( serviceContext, servletReq.getSession()); OAuthStateManager.setOAuthState(userToken, oAuthStateImpl); } else { PortalGuestSessionOAuthStateImpl oAuthStateImpl = new PortalGuestSessionOAuthStateImpl( servletReq.getSession()); OAuthStateManager.setOAuthState(userToken, oAuthStateImpl); } oAuthState = OAuthStateManager.getOAuthState(userToken); if (userTokenObj.p_auth != null && userTokenObj.p_auth.trim().length() > 0) { oAuthState.setPAuth(userTokenObj.p_auth); _log.debug("Received p_auth parameter from portlet: " + userTokenObj.p_auth); } } else { // ... instantiate a new OAuthState considering a web browser as client // If a portlet is the client, then the portlet should have created the OAuthState by now! OAuthStateManager.setOAuthState(userToken, new HttpSessionOAuthStateImpl(servletReq.getSession())); oAuthState = OAuthStateManager.getOAuthState(userToken); } } return oAuthState; }