List of usage examples for org.apache.commons.codec.digest DigestUtils sha1Hex
public static String sha1Hex(String data)
From source file:CSVTools.CsvToolsApi.java
/** * Calculate a SHA1-Hash from a string/* www . j a va2 s . c om*/ * @param inputString * @return * @throws NoSuchAlgorithmException */ public static String calculateSHA1HashFromString(String inputString) throws NoSuchAlgorithmException { try { crypto.update(inputString.getBytes("utf8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } String hash = DigestUtils.sha1Hex(crypto.digest()); return hash; }
From source file:com.qcloud.PicCloud.java
public SliceUploadInfo initUploadSlice(String fileId, byte[] data, int fileSize, int sliceSize, String session) {/*from ww w .j a v a2 s .co m*/ SliceUploadInfo info = new SliceUploadInfo(); //?sha String sha = DigestUtils.sha1Hex(data); // create sign long expired = System.currentTimeMillis() / 1000 + 2592000; String sign = getSign(expired); if (null == sign) { setError(-1, "create app sign failed"); return null; } HashMap<String, String> header = new HashMap<String, String>(); header.put("Authorization", sign); header.put("Host", "web.image.myqcloud.com"); HashMap<String, Object> body = new HashMap<String, Object>(); body.put("op", "upload_slice"); body.put("sha", sha); body.put("filesize", fileSize); if (sliceSize > 0) { body.put("slice_size", sliceSize); } if ("".equals(session)) { body.put("session", session); } String url = getUrl("0", fileId); JSONObject rspData = null; try { String rsp = mClient.post(url, header, body, null); rspData = getResponse(rsp); if (null == rspData || false == rspData.has("data")) { setError(-1, "qcloud api response error, rsp=" + rsp); return null; } rspData = rspData.getJSONObject("data"); } catch (Exception e) { setError(-1, "url exception, e=" + e.toString()); return null; } try { if (rspData.has("url")) { // info.finishFlag = true; info.url = rspData.getString("url"); info.downloadUrl = rspData.getString("download_url"); info.fileId = rspData.getString("fileid"); if (rspData.has("info") && rspData.getJSONArray("info").length() > 0) { info.width = rspData.getJSONArray("info").getJSONObject(0).getJSONObject("0").getInt("width"); info.height = rspData.getJSONArray("info").getJSONObject(0).getJSONObject("0").getInt("height"); } } else if (rspData.has("session")) { info.finishFlag = false; info.reqUrl = url; info.sign = sign; info.session = rspData.getString("session"); info.fileSize = fileSize; info.offset = rspData.getInt("offset"); info.sliceSize = rspData.getInt("slice_size"); } else { setError(-1, "qcloud api response data error"); return null; } } catch (JSONException e) { setError(-1, "json exception, e=" + e.toString()); return null; } return info; }
From source file:com.nebkat.plugin.text.TextPlugin.java
@EventHandler @CommandFilter("hash") public void onHashCommand(CommandEvent e) { if (e.getParams().length < 2) { e.showUsage(getBot());/*from ww w . ja va2 s .com*/ return; } String algorithm = e.getParams()[0]; String text = e.getRawParams().substring(algorithm.length() + 1); String result = "Algorithm unsupported"; if (algorithm.equalsIgnoreCase("md5")) { result = DigestUtils.md5Hex(text); } else if (algorithm.equalsIgnoreCase("md2")) { result = DigestUtils.md2Hex(text); } else if (algorithm.equalsIgnoreCase("sha1") || algorithm.equalsIgnoreCase("sha")) { result = DigestUtils.sha1Hex(text); } else if (algorithm.equalsIgnoreCase("sha256")) { result = DigestUtils.sha256Hex(text); } else if (algorithm.equalsIgnoreCase("sha384")) { result = DigestUtils.sha384Hex(text); } else if (algorithm.equalsIgnoreCase("sha512")) { result = DigestUtils.sha512Hex(text); } Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": " + result); }
From source file:edu.kit.dama.staging.processor.impl.InputHashOP.java
/** * Hash a single file using the internally defined hash algorithm. * * @param pFile The file to hash/*from ww w .j a va 2s . com*/ * * @return The hash value * * @throws IOException If pFile cannot be read */ private String hashFile(File pFile) throws IOException { LOGGER.debug("Hashing file {}", pFile.getAbsolutePath()); InputStream is = null; try { is = new FileInputStream(pFile); String hash; switch (hashType) { case SHA: hash = DigestUtils.sha1Hex(is); break; case SHA256: hash = DigestUtils.sha256Hex(is); break; case SHA384: hash = DigestUtils.sha384Hex(is); break; case SHA512: hash = DigestUtils.sha512Hex(is); break; default: hash = DigestUtils.md5Hex(is); } return hash; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { //ignore } } } }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Authenticates and retrieves the user by using the given list of available AD LDAP servers. * // w ww .j av a 2 s . c o m * @param password * If this is {@link #NO_AUTHENTICATION}, the authentication is not performed, and just the retrieval * would happen. * @throws UsernameNotFoundException * The user didn't exist. * @return never null */ @SuppressFBWarnings(value = "ES_COMPARING_PARAMETER_STRING_WITH_EQ", justification = "Intentional instance check.") public UserDetails retrieveUser(final String username, final String password, final ActiveDirectoryDomain domain, final List<SocketInfo> ldapServers) { UserDetails userDetails; String hashKey = username + "@@" + DigestUtils.sha1Hex(password); final String bindName = domain.getBindName(); final String bindPassword = Secret.toString(domain.getBindPassword()); try { final ActiveDirectoryUserDetail[] cacheMiss = new ActiveDirectoryUserDetail[1]; userDetails = userCache.get(hashKey, new Callable<UserDetails>() { public UserDetails call() throws AuthenticationException { DirContext context; boolean anonymousBind = false; // did we bind anonymously? // LDAP treats empty password as anonymous bind, so we need to reject it if (StringUtils.isEmpty(password)) { throw new BadCredentialsException("Empty password"); } String userPrincipalName = getPrincipalName(username, domain.getName()); String samAccountName = userPrincipalName.substring(0, userPrincipalName.indexOf('@')); if (bindName != null) { // two step approach. Use a special credential to obtain DN for the // user trying to login, then authenticate. try { context = descriptor.bind(bindName, bindPassword, ldapServers, props); anonymousBind = false; } catch (BadCredentialsException e) { throw new AuthenticationServiceException( "Failed to bind to LDAP server with the bind name/password", e); } } else { if (password.equals(NO_AUTHENTICATION)) { anonymousBind = true; } try { // if we are just retrieving the user, try using anonymous bind by empty password (see RFC 2829 5.1) // but if that fails, that's not BadCredentialException but UserMayOrMayNotExistException context = descriptor.bind(userPrincipalName, anonymousBind ? "" : password, ldapServers, props); } catch (BadCredentialsException e) { if (anonymousBind) // in my observation, if we attempt an anonymous bind and AD doesn't allow it, it still passes the bind method // and only fail later when we actually do a query. So perhaps this is a dead path, but I'm leaving it here // anyway as a precaution. throw new UserMayOrMayNotExistException( "Unable to retrieve the user information without bind DN/password configured"); throw e; } } try { // locate this user's record final String domainDN = toDC(domain.getName()); Attributes user = new LDAPSearchBuilder(context, domainDN).subTreeScope() .searchOne("(& (userPrincipalName={0})(objectCategory=user))", userPrincipalName); if (user == null) { // failed to find it. Fall back to sAMAccountName. // see http://www.nabble.com/Re%3A-Hudson-AD-plug-in-td21428668.html LOGGER.log(Level.FINE, "Failed to find {0} in userPrincipalName. Trying sAMAccountName", userPrincipalName); user = new LDAPSearchBuilder(context, domainDN).subTreeScope() .searchOne("(& (sAMAccountName={0})(objectCategory=user))", samAccountName); if (user == null) { throw new UsernameNotFoundException( "Authentication was successful but cannot locate the user information for " + username); } } LOGGER.fine("Found user " + username + " : " + user); Object dnObject = user.get(DN_FORMATTED).get(); if (dnObject == null) { throw new AuthenticationServiceException("No distinguished name for " + username); } String dn = dnObject.toString(); LdapName ldapName = new LdapName(dn); String dnFormatted = ldapName.toString(); if (bindName != null && !password.equals(NO_AUTHENTICATION)) { // if we've used the credential specifically for the bind, we // need to verify the provided password to do authentication LOGGER.log(Level.FINE, "Attempting to validate password for DN={0}", dn); DirContext test = descriptor.bind(dnFormatted, password, ldapServers, props); // Binding alone is not enough to test the credential. Need to actually perform some query operation. // but if the authentication fails this throws an exception try { new LDAPSearchBuilder(test, domainDN).searchOne( "(& (userPrincipalName={0})(objectCategory=user))", userPrincipalName); } finally { closeQuietly(test); } } Set<GrantedAuthority> groups = resolveGroups(domainDN, dnFormatted, context); groups.add(SecurityRealm.AUTHENTICATED_AUTHORITY); cacheMiss[0] = new ActiveDirectoryUserDetail(username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]), getStringAttribute(user, "displayName"), getStringAttribute(user, "mail"), getStringAttribute(user, "telephoneNumber")); return cacheMiss[0]; } catch (NamingException e) { if (anonymousBind && e.getMessage().contains("successful bind must be completed") && e.getMessage().contains("000004DC")) { // sometimes (or always?) anonymous bind itself will succeed but the actual query will fail. // see JENKINS-12619. On my AD the error code is DSID-0C0906DC throw new UserMayOrMayNotExistException( "Unable to retrieve the user information without bind DN/password configured"); } LOGGER.log(Level.WARNING, String.format("Failed to retrieve user information for %s", username), e); throw new BadCredentialsException("Failed to retrieve user information for " + username, e); } finally { closeQuietly(context); } } }); if (cacheMiss[0] != null) { threadPoolExecutor.execute(new Runnable() { @Override public void run() { final String threadName = Thread.currentThread().getName(); Thread.currentThread() .setName(threadName + " updating-cache-for-user-" + cacheMiss[0].getUsername()); LOGGER.log(Level.FINEST, "Starting the cache update {0}", new Date()); try { long t0 = System.currentTimeMillis(); cacheMiss[0].updateUserInfo(); LOGGER.log(Level.FINEST, "Finished the cache update {0}", new Date()); long t1 = System.currentTimeMillis(); LOGGER.log(Level.FINE, "The cache for user {0} took {1} msec", new Object[] { cacheMiss[0].getUsername(), String.valueOf(t1 - t0) }); } finally { Thread.currentThread().setName(threadName); } } }); } } catch (UncheckedExecutionException e) { Throwable t = e.getCause(); if (t instanceof AuthenticationException) { AuthenticationException authenticationException = (AuthenticationException) t; throw authenticationException; } else { throw new CacheAuthenticationException( "Authentication failed because there was a problem caching user " + username, e); } } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "There was a problem caching user " + username, e); throw new CacheAuthenticationException( "Authentication failed because there was a problem caching user " + username, e); } // We need to check the password when the user is cached so it doesn't get automatically authenticated // without verifying the credentials if (password != null && !password.equals(NO_AUTHENTICATION) && userDetails != null && !password.equals(userDetails.getPassword())) { throw new BadCredentialsException("Failed to retrieve user information from the cache for " + username); } return userDetails; }
From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java
/** * Method to generate and return digest of the PDF contents * @param content in String which is actually the digest of the file * @return String, the digest of the input file *//*www . ja va 2 s . c o m*/ public static String getDocumentDigest(String content) { logger.info("Returning digest"); return DigestUtils.sha1Hex(content); }
From source file:de.elomagic.maven.http.HTTPMojo.java
private void checkFile(final Path path) throws Exception { String fileDigest;//from w w w .ja v a 2 s. com try (InputStream in = Files.newInputStream(path)) { switch (digestType.toLowerCase()) { case "md5": fileDigest = DigestUtils.md5Hex(in); break; case "sha1": fileDigest = DigestUtils.sha1Hex(in); break; case "sha256": fileDigest = DigestUtils.sha256Hex(in); break; case "sha384": fileDigest = DigestUtils.sha384Hex(in); break; case "sha512": fileDigest = DigestUtils.sha512Hex(in); break; default: throw new Exception("Digest type \"" + digestType + "\" not supported."); } } if (!fileDigest.equalsIgnoreCase(digest)) { throw new Exception( digestType + " digest check failed. File=\"" + fileDigest + "\", Digest=\"" + digest + "\""); } }
From source file:io.github.rcarlosdasilva.weixin.api.weixin.impl.CertificateApiImpl.java
@Override public JsapiSignature generateJsapiSignature(String url) { WeixinAccount account = Registry.lookup(this.accountKey); String ticket = Weixin.with(this.accountKey).certificate().askJsTicket(); String timestamp = Long.toString(System.currentTimeMillis() / 1000); String nonce = UUID.randomUUID().toString(); String raw = new StringBuilder("jsapi_ticket=").append(ticket).append("&noncestr=").append(nonce) .append("×tamp=").append(timestamp).append("&url=").append(url).toString(); String signature = null;/*from w w w . j a va2 s . c o m*/ signature = DigestUtils.sha1Hex(raw); return new JsapiSignature(account.getAppId(), ticket, signature, url, timestamp, nonce); }
From source file:net.solarnetwork.node.setup.obr.OBRProvisionTask.java
private void moveTemporaryDownloadedPluginFile(Resource resource, File outputFile, File tmpOutputFile) { if (outputFile.exists()) { // if the file has not changed, just delete tmp file InputStream outputFileInputStream = null; InputStream tmpOutputFileInputStream = null; try {/*from w w w.j a va 2s.c om*/ outputFileInputStream = new FileInputStream(outputFile); tmpOutputFileInputStream = new FileInputStream(tmpOutputFile); String outputFileHash = DigestUtils.sha1Hex(outputFileInputStream); String tmpOutputFileHash = DigestUtils.sha1Hex(tmpOutputFileInputStream); if (tmpOutputFileHash.equals(outputFileHash)) { // file unchanged, so just delete tmp file tmpOutputFile.delete(); } else { LOG.debug("Bundle {} version {} content updated", resource.getSymbolicName(), resource.getVersion()); outputFile.delete(); tmpOutputFile.renameTo(outputFile); } } catch (IOException e) { throw new RuntimeException("Error downloading plugin " + resource.getSymbolicName(), e); } finally { if (outputFileInputStream != null) { try { outputFileInputStream.close(); } catch (IOException e) { // ignore; } } if (tmpOutputFileInputStream != null) { try { tmpOutputFileInputStream.close(); } catch (IOException e) { // ignore } } } } else { // rename tmp file tmpOutputFile.renameTo(outputFile); } }
From source file:net.solarnetwork.node.setup.s3.S3SetupManager.java
/** * Download and install all setup objects in a given configuration. * //w w w.ja v a 2 s . c o m * @param config * the configuration to apply * @return the set of absolute paths of all installed files (or an empty set * if nothing installed) * @throws IOException * if an IO error occurs */ private Set<Path> applySetupObjects(S3SetupConfiguration config) throws IOException { Set<Path> installed = new LinkedHashSet<>(); for (String dataObjKey : config.getObjects()) { if (!TARBALL_PAT.matcher(dataObjKey).find()) { log.warn("S3 setup resource {} not a supported type; skipping"); continue; } S3Object obj = s3Client.getObject(dataObjKey); if (obj == null) { log.warn("Data object {} not found, cannot apply setup", dataObjKey); continue; } File workDir = new File(workDirectory); if (!workDir.exists()) { if (!workDir.mkdirs()) { log.warn("Unable to create work dir {}", workDir); } } // download the data object to the work dir String dataObjFilename = DigestUtils.sha1Hex(dataObjKey); File dataObjFile = new File(workDir, dataObjFilename); try (InputStream in = obj.getObjectContent(); OutputStream out = new BufferedOutputStream(new FileOutputStream(dataObjFile))) { log.info("Downloading S3 setup resource {} -> {}", dataObjKey, dataObjFile); FileCopyUtils.copy(obj.getObjectContent(), out); // extract tarball List<Path> extractedPaths = extractTarball(dataObjFile); installed.addAll(extractedPaths); } finally { if (dataObjFile.exists()) { dataObjFile.delete(); } } } if (!installed.isEmpty()) { log.info("Installed files from objects {}: {}", Arrays.asList(config.getObjects()), installed); } return installed; }