Java Code Examples for org.apache.commons.codec.digest.DigestUtils#sha256Hex()
The following examples show how to use
org.apache.commons.codec.digest.DigestUtils#sha256Hex() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedisConfig.java From sk-admin with Apache License 2.0 | 6 votes |
/** * 自定义缓存key生成策略,默认将使用该策略 */ @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { Map<String, Object> container = new HashMap<>(3); Class<?> targetClassClass = target.getClass(); // 类地址 container.put("class", targetClassClass.toGenericString()); // 方法名称 container.put("methodName", method.getName()); // 包名称 container.put("package", targetClassClass.getPackage()); // 参数列表 for (int i = 0; i < params.length; i++) { container.put(String.valueOf(i), params[i]); } // 转为JSON字符串 String jsonString = JSON.toJSONString(container); // 做SHA256 Hash计算,得到一个SHA256摘要作为Key return DigestUtils.sha256Hex(jsonString); }; }
Example 2
Source File: CachingTesseractOCRParser.java From extract with MIT License | 5 votes |
private void cachedParse(final TikaInputStream tis, final ContentHandler handler, final Metadata metadata, final ParseContext context, final TesseractOCRConfig config, final boolean inline) throws IOException, SAXException, TikaException, InterruptedException { final String hash; try (final InputStream buffered = Files.newInputStream(tis.getPath())) { hash = DigestUtils.sha256Hex(buffered); } final Path cachePath = outputPath.resolve(hash); final Path cacheLock = outputPath.resolve(hash + ".lock"); // Acquire a lock both for reading and for writing. // If the lock can't be acquired, parse without caching. if (!acquireLock(config, cacheLock)) { fallbackParse(tis, handler, metadata, context, config, inline); return; } // You won't know for sure until you try.... try (final Reader reader = Files.newBufferedReader(cachePath, UTF_8)) { cacheHit(); readFromCache(reader, handler, metadata); } catch (final NoSuchFileException e) { final Path cacheTemp = outputPath.resolve(hash + ".tmp"); // Write to a temporary file and only move to the final path if parsing completes successfully. // This way we ensure that we don't cache partial results from Tesseract if there's an error. try (final Writer writer = Files.newBufferedWriter(cacheTemp, UTF_8, StandardOpenOption.CREATE)) { cacheMiss(); parseToCache(tis, handler, metadata, context, config, inline, writer); } Files.move(cacheTemp, cachePath, StandardCopyOption.ATOMIC_MOVE); } finally { Files.deleteIfExists(cacheLock); } }
Example 3
Source File: AlipayCore.java From shopping with Apache License 2.0 | 5 votes |
/** * 生成文件摘要 * @param strFilePath 文件路径 * @param file_digest_type 摘要算法 * @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if(file_digest_type.equals("MD5")){ return DigestUtils.md5Hex(file.createInputStream()); } else if(file_digest_type.equals("SHA")) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } }
Example 4
Source File: CompressedTextFile.java From SPADE with GNU General Public License v3.0 | 5 votes |
@Override public boolean putVertex(AbstractVertex incomingVertex) { try { String vertexHash = DigestUtils.sha256Hex(incomingVertex.toString()); Integer vertexId = nextVertexID; nextVertexID ++; hashToID.put(vertexHash, vertexId); StringBuilder annotationString = new StringBuilder(); //annotationString.append("VERTEX (" + vertexId + "): {"); for (Map.Entry<String, String> currentEntry : incomingVertex.getCopyOfAnnotations().entrySet()) { String key = currentEntry.getKey(); String value = currentEntry.getValue(); if (key == null || value == null) { continue; } annotationString.append(key); annotationString.append(":"); annotationString.append(value); annotationString.append(","); } //annotationString.append("}\n"); String vertexString = annotationString.toString(); //outputFile.write(vertexString); byte [] input = vertexString.getBytes("UTF-8"); byte [] output = new byte[input.length + 100]; compresser.setInput(input); compresser.finish(); int compressedDataLength = compresser.deflate(output); put(annotationsWriter, vertexId, output); compresser.reset(); return true; } catch (Exception exception) { Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, exception); return false; } }
Example 5
Source File: ChecksumUtil.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
public static String checksum(String text) { if (text == null) { throw new IllegalArgumentException("Cannot calculate checksum of null"); } return DigestUtils.sha256Hex(text); }
Example 6
Source File: AlipayCore.java From roncoo-pay with Apache License 2.0 | 5 votes |
/** * 生成文件摘要 * @param strFilePath 文件路径 * @param file_digest_type 摘要算法 * @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if(file_digest_type.equals("MD5")){ return DigestUtils.md5Hex(file.createInputStream()); } else if(file_digest_type.equals("SHA")) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } }
Example 7
Source File: ReceiptLogicImpl.java From icure-backend with GNU General Public License v2.0 | 5 votes |
@Override public void addReceiptAttachment(Receipt receipt, ReceiptBlobType blobType, byte[] payload) { String newAttachmentId = DigestUtils.sha256Hex(payload); receipt.getAttachmentIds().put(blobType, newAttachmentId); updateEntities(Collections.singletonList(receipt)); AttachmentInputStream a = new AttachmentInputStream(newAttachmentId, new ByteArrayInputStream(payload), "application/octet-stream"); receipt.setRev(receiptDAO.createAttachment(receipt.getId(), receipt.getRev(), a)); }
Example 8
Source File: BitbucketServerScmTest.java From blueocean-plugin with MIT License | 5 votes |
/** * Checks different server urls and consistency of generated credentialId */ @Test public void getScmNormalizedUrlTest() throws IOException, UnirestException { String credentialId = createCredential(BitbucketServerScm.ID); String apiUrl = this.apiUrl; String normalizedUrl = BitbucketEndpointConfiguration.normalizeServerUrl(apiUrl); String expectedCredId = BitbucketServerScm.ID+":"+ DigestUtils.sha256Hex(normalizedUrl); assertEquals(credentialId, expectedCredId); Map r = new RequestBuilder(baseUrl) .status(200) .jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), authenticatedUser.getId())) .get("/organizations/jenkins/scm/"+BitbucketServerScm.ID+String.format("?apiUrl=%s",apiUrl)) .build(Map.class); assertEquals(normalizedUrl, r.get("uri")); assertEquals(expectedCredId, r.get("credentialId")); String apiUrlWithSlash = this.apiUrl+"/"; assertNotEquals(apiUrl, apiUrlWithSlash); String normalizedUrlWithSlash = BitbucketEndpointConfiguration.normalizeServerUrl(apiUrl); assertEquals(normalizedUrl, normalizedUrlWithSlash); String expectedCredIdWithSlash = BitbucketServerScm.ID+":"+ DigestUtils.sha256Hex(normalizedUrlWithSlash); assertEquals(expectedCredId, expectedCredIdWithSlash); r = new RequestBuilder(baseUrl) .status(200) .jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), authenticatedUser.getId())) .get("/organizations/jenkins/scm/"+BitbucketServerScm.ID+String.format("?apiUrl=%s",apiUrl)) .build(Map.class); assertEquals(expectedCredId, r.get("credentialId")); assertEquals(normalizedUrl, r.get("uri")); }
Example 9
Source File: RangerPolicyResourceSignature.java From ranger with Apache License 2.0 | 5 votes |
/** * Only added for testability. Do not make public * @param string */ RangerPolicyResourceSignature(String string) { _policy = null; if (string == null) { _string = ""; } else { _string = string; } _hash = DigestUtils.sha256Hex(_string); }
Example 10
Source File: SimplePasswordEncoder.java From keycloak-user-migration-provider with Apache License 2.0 | 4 votes |
@Override public String encode(String rawPassword, String salt) { return DigestUtils.sha256Hex(rawPassword + salt); }
Example 11
Source File: SchemaSigner.java From apicurio-studio with Apache License 2.0 | 4 votes |
public String getSignature() { if (this.sigSource.length() == 0) { return null; } return DigestUtils.sha256Hex(this.sigSource.toString()); }
Example 12
Source File: LoginServiceImpl.java From spring-boot-plus with Apache License 2.0 | 4 votes |
@Transactional(rollbackFor = Exception.class) @Override public LoginSysUserTokenVo login(LoginParam loginParam) throws Exception { // 校验验证码 checkVerifyCode(loginParam.getVerifyToken(), loginParam.getCode()); String username = loginParam.getUsername(); // 从数据库中获取登录用户信息 SysUser sysUser = getSysUserByUsername(username); if (sysUser == null) { log.error("登录失败,loginParam:{}", loginParam); throw new AuthenticationException("用户名或密码错误"); } if (StateEnum.DISABLE.getCode().equals(sysUser.getState())) { throw new AuthenticationException("账号已禁用"); } // 实际项目中,前端传过来的密码应先加密 // 原始密码明文:123456 // 原始密码前端加密:sha256(123456) // 后台加密规则:sha256(sha256(123456) + salt) String encryptPassword = PasswordUtil.encrypt(loginParam.getPassword(), sysUser.getSalt()); if (!encryptPassword.equals(sysUser.getPassword())) { throw new AuthenticationException("用户名或密码错误"); } // 将系统用户对象转换成登录用户对象 LoginSysUserVo loginSysUserVo = SysUserConvert.INSTANCE.sysUserToLoginSysUserVo(sysUser); // 获取部门 SysDepartment sysDepartment = sysDepartmentService.getById(sysUser.getDepartmentId()); if (sysDepartment == null) { throw new AuthenticationException("部门不存在"); } if (!StateEnum.ENABLE.getCode().equals(sysDepartment.getState())) { throw new AuthenticationException("部门已禁用"); } loginSysUserVo.setDepartmentId(sysDepartment.getId()) .setDepartmentName(sysDepartment.getName()); // 获取当前用户角色 Long roleId = sysUser.getRoleId(); SysRole sysRole = sysRoleService.getById(roleId); if (sysRole == null) { throw new AuthenticationException("角色不存在"); } if (StateEnum.DISABLE.getCode().equals(sysRole.getState())) { throw new AuthenticationException("角色已禁用"); } loginSysUserVo.setRoleId(sysRole.getId()) .setRoleName(sysRole.getName()) .setRoleCode(sysRole.getCode()); // 获取当前用户权限 Set<String> permissionCodes = sysRolePermissionService.getPermissionCodesByRoleId(roleId); if (CollectionUtils.isEmpty(permissionCodes)) { throw new AuthenticationException("权限列表不能为空"); } loginSysUserVo.setPermissionCodes(permissionCodes); // 获取数据库中保存的盐值 String newSalt = SaltUtil.getSalt(sysUser.getSalt(), jwtProperties); // 生成token字符串并返回 Long expireSecond = jwtProperties.getExpireSecond(); String token = JwtUtil.generateToken(username, newSalt, Duration.ofSeconds(expireSecond)); log.debug("token:{}", token); // 创建AuthenticationToken JwtToken jwtToken = JwtToken.build(token, username, newSalt, expireSecond); boolean enableShiro = springBootPlusProperties.getShiro().isEnable(); if (enableShiro) { // 从SecurityUtils里边创建一个 subject Subject subject = SecurityUtils.getSubject(); // 执行认证登录 subject.login(jwtToken); } else { log.warn("未启用Shiro"); } // 缓存登录信息到Redis loginRedisService.cacheLoginInfo(jwtToken, loginSysUserVo); log.debug("登录成功,username:{}", username); // 缓存登录信息到redis String tokenSha256 = DigestUtils.sha256Hex(token); redisTemplate.opsForValue().set(tokenSha256, loginSysUserVo, 1, TimeUnit.DAYS); // 返回token和登录用户信息对象 LoginSysUserTokenVo loginSysUserTokenVo = new LoginSysUserTokenVo(); loginSysUserTokenVo.setToken(token); loginSysUserTokenVo.setLoginSysUserVo(loginSysUserVo); return loginSysUserTokenVo; }
Example 13
Source File: UserService.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 4 votes |
protected String computeSHA256(String password, int iterations, String salt, String pepper){ /* Given an hash function "f", we have f(password) = hash the main point is that, even if one knows the details of "f" and has the hash, then it is extremely difficult to derive the input password, ie find a function "g" such that g(hash) = password */ String hash = password + salt + pepper; /* The password is combined with a "salt" to avoid: 1) two users with same password having same hash. Even if one password gets compromised, an attacker would have no way to know if any other user has the same password 2) make nearly impossible a brute force attack based on "rainbow tables", ie pre-computed values of all hashes from password strings up to length N. This is because now the hashed string will be at least the length of the salt (eg 26) regardless of the length of the password. Note: a hacker accessing the database can read the "salt", but would not be able to read the "pepper". Note: DigestUtils from commons-codec library is just an utility to simplify the usage of Java API own MessageDigest class */ for(int i=0; i<iterations; i++) { hash = DigestUtils.sha256Hex(hash); } return hash; }
Example 14
Source File: StringTools.java From o2oa with GNU Affero General Public License v3.0 | 4 votes |
public static String sha(Object o) { String str = Objects.toString(o, ""); return DigestUtils.sha256Hex(str); }
Example 15
Source File: S3GetSecretRequest.java From hadoop-ozone with Apache License 2.0 | 4 votes |
@Override public OMRequest preExecute(OzoneManager ozoneManager) throws IOException { GetS3SecretRequest s3GetSecretRequest = getOmRequest().getGetS3SecretRequest(); // Generate S3 Secret to be used by OM quorum. String kerberosID = s3GetSecretRequest.getKerberosID(); UserGroupInformation user = ProtobufRpcEngine.Server.getRemoteUser(); if (!user.getUserName().equals(kerberosID)) { throw new OMException("User mismatch. Requested user name is " + "mismatched " + kerberosID +", with current user " + user.getUserName(), OMException.ResultCodes.USER_MISMATCH); } String s3Secret = DigestUtils.sha256Hex(OmUtils.getSHADigest()); UpdateGetS3SecretRequest updateGetS3SecretRequest = UpdateGetS3SecretRequest.newBuilder() .setAwsSecret(s3Secret) .setKerberosID(kerberosID).build(); // Client issues GetS3Secret request, when received by OM leader // it will generate s3Secret. Original GetS3Secret request is // converted to UpdateGetS3Secret request with the generated token // information. This updated request will be submitted to Ratis. In this // way S3Secret created by leader, will be replicated across all // OMs. With this approach, original GetS3Secret request from // client does not need any proto changes. OMRequest.Builder omRequest = OMRequest.newBuilder() .setUserInfo(getUserInfo()) .setUpdateGetS3SecretRequest(updateGetS3SecretRequest) .setCmdType(getOmRequest().getCmdType()) .setClientId(getOmRequest().getClientId()); if (getOmRequest().hasTraceID()) { omRequest.setTraceID(getOmRequest().getTraceID()); } return omRequest.build(); }
Example 16
Source File: ChecksumSHA256Impl.java From big-c with Apache License 2.0 | 4 votes |
public String computeChecksum(InputStream in) throws IOException { return DigestUtils.sha256Hex(in); }
Example 17
Source File: EncryptionUtil.java From OnlineFriend with Apache License 2.0 | 4 votes |
/** * sha256 * */ public static String sha256Hex(String data){ return DigestUtils.sha256Hex(data); }
Example 18
Source File: HashUtils.java From metron with Apache License 2.0 | 4 votes |
public static String getMessageHash(JSONObject message) { return DigestUtils.sha256Hex(message.toJSONString().getBytes(UTF_8)); }
Example 19
Source File: CodecUtil.java From common_gui_tools with Apache License 2.0 | 3 votes |
/** * Calculates the SHA-256 digest and returns the value as a hex string. * * @param string String * @param charSet CharSet * @return <code>String</code> SHA-256 string * @throws UnsupportedEncodingException unsupported encoding exception */ public static String encryptSha256(String string, String charSet) throws UnsupportedEncodingException { if (string == null) { return null; } return DigestUtils.sha256Hex(string.getBytes(charSet)); }
Example 20
Source File: Hash.java From blockchain with Apache License 2.0 | 2 votes |
public static String sha3String(byte[] input) { return DigestUtils.sha256Hex(input); }