Java Code Examples for org.apache.commons.codec.digest.DigestUtils.sha256Hex()

The following are Jave code examples for showing how to use sha256Hex() of the org.apache.commons.codec.digest.DigestUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: TOSCAna   File: BaseDockerfileTest.java   View Source Code Vote up 8 votes
public String buildSHADockerfile() throws Exception {
    File bindir = new File(inputDir, "bin");
    bindir.mkdirs();
    byte[] data = new byte[1024 * 1024 * 10];
    new Random().nextBytes(data);

    FileUtils.writeByteArrayToFile(new File(bindir, "test.bin"), data);

    builder.run("apt update")
        .run("apt upgrade -y")
        .workdir("/hello")
        .copyFromCsar("bin", "bin", ".")
        .compressRunCommands()
        .entrypoint("sha256sum", "test.bin");

    builder.write();
    return DigestUtils.sha256Hex(data);
}
 
Example 2
Project: webcron   File: HashUtils.java   View Source Code Vote up 7 votes
/**
 * @param message {@link String}
 * @param type    {@link HashType}
 * @return {@link String}
 */
private static String sha(String message, HashType type) {
    switch (type) {
        case SHA1:
            return DigestUtils.sha1Hex(message);
        case SHA256:
            return DigestUtils.sha256Hex(message);
        case SHA512:
            return DigestUtils.sha512Hex(message);
        default:
            return DigestUtils.sha256Hex(message);
    }
}
 
Example 3
Project: couchmove   File: FileUtils.java   View Source Code Vote up 7 votes
/**
 * If the file is a Directory, calculate the checksum of all files in this directory (one level)
 * Else, calculate the checksum of the file matching extensions
 *
 * @param filePath   file or folder
 * @param extensions of files to calculate checksum of
 * @return checksum
 */
public static String calculateChecksum(@NotNull Path filePath, String... extensions) {
    if (filePath == null || !Files.exists(filePath)) {
        throw new CouchmoveException("File is null or doesn't exists");
    }
    if (Files.isDirectory(filePath)) {
        return directoryStream(filePath, extensions)
                .sorted(Comparator.comparing(path -> path.getFileName().toString()))
                .map(FileUtils::calculateChecksum)
                .reduce(String::concat)
                .map(DigestUtils::sha256Hex)
                .orElse(null);
    }
    try {
        return DigestUtils.sha256Hex(toByteArray(filePath.toUri()));
    } catch (IOException e) {
        throw new CouchmoveException("Unable to calculate file checksum '" + filePath.getFileName().toString() + "'");
    }
}
 
Example 4
Project: epay   File: AlipayCore.java   View Source Code Vote up 6 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 5
Project: framework   File: AlipayCore.java   View Source Code Vote up 6 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 6
Project: WeiXing_xmu-2016-MrCode   File: AlipayCore.java   View Source Code Vote up 6 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
Project: testing_security_development_enterprise_systems   File: UserEJB.java   View Source Code Vote up 6 votes
@NotNull
protected String computeHash(String password, String salt){

     /*
        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 combined = password + salt;

    /*
        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: DigestUtils from commons-codec library is just an utility to simplify
        the usage of Java API own MessageDigest class
     */

    String hash = DigestUtils.sha256Hex(combined);
    return hash;
}
 
Example 8
Project: minlia-iot   File: XmlSignatureAnnotationHelper.java   View Source Code Vote up 6 votes
/**
 * 根据SinpleField列表生成签名
 *
 * 加2个参数   delimiter,caseConvert
 *
 * @param fieldPaireds SinpleField的列表
 * @param salt partnerApiKey
 * @return 生成的签名字符串
 */
private static String makeSignBySinpleFieldList(List<FieldPaired> fieldPaireds, String salt,
    Boolean excludeKeyParameter, SignatureAlgorithmic algorithmic, String saltParameterPrefix,
    String charset, CaseControl caseControl, String delimiter) {
  List<String> list = fieldPaireds.stream()
      .sorted(new AsciiSortedComparator<>(FieldPaired::getProperty)).map(
          FieldPaired::toString).collect(Collectors.toList());

  //在对象上添加特殊属性, 当不排除时添加
  if (!excludeKeyParameter) {
    if (StringUtils.isEmpty(saltParameterPrefix)) {
      throw new RuntimeException("指定了需要添加KEY=到salt前面, 却没有指定前前缀, 请检查官方文档,再做相应调整");
    }
    list.add(saltParameterPrefix + salt);
  }

  // 未加密字符串
  String unencrypted = "";
  try {
    unencrypted = new String(String.join(delimiter, list).getBytes(), charset);
    //将salt添加到最后面
    if (!StringUtils.isEmpty(salt)) {
      if (excludeKeyParameter) {
        unencrypted += salt;
      }
    }
    log.debug("Unencrypted String is: {}", unencrypted);
  } catch (Exception e) {
    e.printStackTrace();
  }

  String result = "";
  switch (algorithmic) {
    case MD2:
      result = DigestUtils.md2Hex(unencrypted);
      break;
    case MD5:
      result = DigestUtils.md5Hex(unencrypted);
      break;
    case SHA1:
      result = DigestUtils.sha1Hex(unencrypted);
      break;
    case SHA256:
      result = DigestUtils.sha256Hex(unencrypted);
      break;
    case SHA384:
      result = DigestUtils.sha384Hex(unencrypted);
      break;
    case SHA512:
      result = DigestUtils.sha512Hex(unencrypted);
      break;
    default:
      throw new RuntimeException("不支持的签名类型");
  }

  if (null != caseControl) {
    switch (caseControl) {
      case TO_LOWER_CASE:
        result = result.toLowerCase();
        break;
      case TO_UPPER_CASE:
        result = result.toUpperCase();
        break;
    }
  }

  log.debug("Encrypted Signature is: {}", result);
  return result;

}
 
Example 9
Project: k-framework   File: AlipayCore.java   View Source Code Vote up 6 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 10
Project: generator-thundr-gae-react   File: MagicLink.java   View Source Code Vote up 5 votes
public static String hash(String code) {
    return DigestUtils.sha256Hex(code);
}
 
Example 11
Project: generator-thundr-gae-react   File: UserInviteLink.java   View Source Code Vote up 5 votes
public static String hash(String code) {
    return DigestUtils.sha256Hex(code);
}
 
Example 12
Project: OAuth-2.0-Cookbook   File: CustomAuthCodeTokenGranter.java   View Source Code Vote up 5 votes
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = tokenRequest.getRequestParameters();
    String authorizationCode = parameters.get("code");
    String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
    String codeVerifier = parameters.get("code_verifier");

    if (authorizationCode == null) {
        throw new InvalidRequestException("An authorization code must be supplied.");
    }

    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }

    OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();




    // Validates code verifier
    Map<String, String> pendingOauth2RequestParams = pendingOAuth2Request.getRequestParameters();
    String codeChallenge = pendingOauth2RequestParams.get("code_challenge");
    String codeChallengeMethod = pendingOauth2RequestParams.get("code_challenge_method");

    if (codeVerifier == null && codeChallenge != null) {
        // client is using PKCE but did not send the codeVerifier
        throw new InvalidRequestException(
                "Invalid authorization code for current token request.");
    }

    if (codeVerifier != null && codeChallenge != null) {
        String hashed = codeVerifier;
        if ("S256".equals(codeChallengeMethod)) {
            hashed = DigestUtils.sha256Hex(codeVerifier);
        }

        if (!hashed.equalsIgnoreCase(codeChallenge)) {
            throw new InvalidRequestException(
                    "Invalid authorization code for current token request.");
        }
    }



    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the redirect_uri parameter
    String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(
            OAuth2Utils.REDIRECT_URI);

    if ((redirectUri != null || redirectUriApprovalParameter != null)
            && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }

    String pendingClientId = pendingOAuth2Request.getClientId();
    String clientId = tokenRequest.getClientId();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }

    // Secret is not required in the authorization request, so it won't be available
    // in the pendingAuthorizationRequest. We do want to check that a secret is provided
    // in the token request, but that happens elsewhere.

    Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request
            .getRequestParameters());
    // Combine the parameters adding the new ones last so they override if there are any clashes
    combinedParameters.putAll(parameters);

    // Make a new stored request with the combined parameters
    OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);

    Authentication userAuth = storedAuth.getUserAuthentication();

    return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);

}
 
Example 13
Project: testing_security_development_enterprise_systems   File: UserEJB.java   View Source Code Vote up 5 votes
@NotNull
protected String computeHash(String password, String salt){
    String combined = password + salt;
    String hash = DigestUtils.sha256Hex(combined);
    return hash;
}
 
Example 14
Project: testing_security_development_enterprise_systems   File: UserEJB.java   View Source Code Vote up 5 votes
@NotNull
protected String computeHash(String password, String salt){
    String combined = password + salt;
    String hash = DigestUtils.sha256Hex(combined);
    return hash;
}
 
Example 15
Project: Equella   File: Hash.java   View Source Code Vote up 5 votes
@Override
public String getDigest(String value)
{
	return DigestUtils.sha256Hex(SHA256_SALT + value);
}
 
Example 16
Project: hadoop   File: ChecksumSHA256Impl.java   View Source Code Vote up 5 votes
public String computeChecksum(InputStream in) throws IOException {
  return DigestUtils.sha256Hex(in);
}
 
Example 17
Project: CTUConference   File: AttachmentServiceImpl.java   View Source Code Vote up 5 votes
private String generateFileHash(Attachment attachment) {
	String seed = new Date().toString() + attachment.getFileName();
	return DigestUtils.sha256Hex(seed);
}
 
Example 18
Project: qcloudsms_java   File: SmsSenderUtil.java   View Source Code Vote up 4 votes
private static String sha256(String rawString) {
    return DigestUtils.sha256Hex(rawString);
}
 
Example 19
Project: nectar-server   File: Util.java   View Source Code Vote up 2 votes
/**
 * Compute the SHA-256 Hash of a String.
 * @param plaintext The raw text to be hashed.
 * @return The hash of the provided text.
 */
public static String computeSHA256(String plaintext) {
    return DigestUtils.sha256Hex(plaintext);
}
 
Example 20
Project: Dragonfly   File: DigestUtil.java   View Source Code Vote up 2 votes
/**
 * @param target
 * @return
 */
public static String sha256(String target) {
    return DigestUtils.sha256Hex(target);
}