本文整理汇总了Java中org.apache.commons.codec.digest.DigestUtils类的典型用法代码示例。如果您正苦于以下问题:Java DigestUtils类的具体用法?Java DigestUtils怎么用?Java DigestUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DigestUtils类属于org.apache.commons.codec.digest包,在下文中一共展示了DigestUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: calculateChecksum
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
/**
* 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() + "'");
}
}
示例2: blur
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
@RequestMapping(value = "/blur", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> blur(@RequestParam("source") String sourceUrl, HttpServletResponse response) {
if (!StringUtils.startsWithAny(sourceUrl, ALLOWED_PREFIX)) {
return ResponseEntity.badRequest().build();
}
String hash = DigestUtils.sha1Hex(sourceUrl);
try {
ImageInfo info = readCached(hash);
if (info == null) {
info = renderImage(sourceUrl);
if (info != null) {
saveCached(hash, info);
}
}
if (info != null) {
return ResponseEntity.ok()
.contentLength(info.contentLength)
.contentType(MediaType.IMAGE_JPEG)
.body(new InputStreamResource(info.inputStream));
}
} catch (IOException e) {
// fall down
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
示例3: validateSign
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
/**
* 一个简单的签名认证,规则:
* 1. 将请求参数按ascii码排序
* 2. 拼接为a=value&b=value...这样的字符串(不包含sign)
* 3. 混合密钥(secret)进行md5获得签名,与请求的签名进行比较
*/
private boolean validateSign(HttpServletRequest request) {
String requestSign = request.getParameter("sign");//获得请求签名,如sign=19e907700db7ad91318424a97c54ed57
if (StringUtils.isEmpty(requestSign)) {
return false;
}
List<String> keys = new ArrayList<String>(request.getParameterMap().keySet());
keys.remove("sign");//排除sign参数
Collections.sort(keys);//排序
StringBuilder sb = new StringBuilder();
for (String key : keys) {
sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
}
String linkString = sb.toString();
linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'
String secret = "Potato";//密钥,自己修改
String sign = DigestUtils.md5Hex(linkString + secret);//混合密钥md5
return StringUtils.equals(sign, requestSign);//比较
}
示例4: execute
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDetail jobDetail = jobExecutionContext.getJobDetail();
_logger.info("Cron triggered for {0}", jobDetail.getDescription());
JobDataMap dataMap = jobDetail.getJobDataMap();
try {
//Creating entry in redis to avoid duplicate job scheduling
MemcacheService cache = AppFactory.get().getMemcacheService();
String jobKey = "SJOB_" + DigestUtils.md5Hex(dataMap.getString("url"));
if (cache.get(jobKey) == null) {
HttpUtil
.connectMulti(HttpUtil.GET, ConfigUtil.get("task.url") + dataMap.getString("url"), null,
null, null, null);
cache.put(jobKey, true, 1800);
} else {
_logger.warn("Job with url {0} is already scheduled. Doing nothing!!",
dataMap.getString("url"));
}
} catch (Exception e) {
_logger.warn("Scheduled job failed for url {0} with exception {1}", dataMap.getString("url"),
e.getMessage(), e);
}
}
示例5: calculate
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
public static final String calculate(Map<String, ? extends Object> parameters, String appsecret) {
TreeMap<String, Object> params = new TreeMap(parameters);
params.remove("sign");
params.put("appsecret", appsecret);
StringBuilder stringBuilder = new StringBuilder();
Iterator var4 = params.entrySet().iterator();
while(var4.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry)var4.next();
stringBuilder.append(((String)entry.getKey()).trim());
stringBuilder.append("=");
stringBuilder.append(entry.getValue().toString().trim());
stringBuilder.append("&");
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
return DigestUtils.sha1Hex(stringBuilder.toString());
}
示例6: computeFileDigest
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
/**
* Computes the digest of the contents of the file this database belongs to.
*
* @return a digest, representing the contents of the file
* @throws IOException in the case of an error during IO operations
*/
private String computeFileDigest() throws IOException {
final BasicFileAttributes attr =
Files.readAttributes(Paths.get(fileDatabase.getFileName()), BasicFileAttributes.class);
return DigestUtils.sha512Hex(fileDatabase.getFileName() + attr.lastModifiedTime() + attr.size());
}
示例7: handle
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
@Override
public void handle(CrawlerResult crawlerResult, CrawlerRequest request) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(getFile(path +
DigestUtils.md5Hex(request.getUrl()) + ".html")),"UTF-8"));
Map<String , Object> data = crawlerResult.getAllData();
for (String key : data.keySet()) {
pw.println(key + ": \t" + data.get(key));
}
pw.flush();
} catch (IOException e) {
logger.error("error occurred : {}", e);
}finally {
pw.close();
}
}
示例8: computeHash
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
@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;
}
示例9: getAbstract
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
/**
* 生成文件摘要
*
* @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 "";
}
}
示例10: getPushUrl
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
/**
* 获取推流地址 如果不传key和过期时间,将返回不含防盗链的url
*/
public static String getPushUrl(StreamUrlConfig config) {
String liveCode = getStreamId(config.getBizId(), config.getRoomId(), config.getUserId(), config.getDataType());
if(isNotBlank(config.getKey()) && config.getExpireTime() != null){
String txTime = Long.toHexString(config.getExpireTime().getTime()/1000).toUpperCase();
String input = new StringBuilder().append(config.getKey()).append(liveCode)
.append(txTime).toString();
try {
String txSecret = DigestUtils.md5Hex(input.getBytes("UTF-8"));
return "rtmp://"+config.getBizId()+".livepush.myqcloud.com/live/"+liveCode+"?bizid="+config.getBizId()+"&txSecret="+txSecret+"&txTime="+txTime;
} catch (Exception e) {
Throwables.propagate(e);
}
}
return "rtmp://"+config.getBizId()+".livepush.myqcloud.com/live/"+liveCode;
}
示例11: push
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
@Override
public void push(Request request, ISpider spider) {
Jedis jedis = pool.getResource();
if (Const.HttpMethod.POST == request.getMethod()
|| !isDuplicate(request, spider)) {
log.debug("push to queue {}", request.getUrl());
try {
jedis.rpush(getQueueKey(spider), request.getUrl());
String field = DigestUtils.md5Hex(request.getUrl());
byte[] data=SerializationUtils.serialize(request);
jedis.hset((ITEM_PREFIX + spider.getName()).getBytes(), field.getBytes(), data);
} finally {
jedis.close();
}
}
}
示例12: openJscriptStepEditor
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
private void openJscriptStepEditor() {
Project project = dbo.getProject();
try {
// Create private folder if it does not exist
FileUtils.createFolderIfNotExist(project.getDirPath(), "_private");
String fileName = FileUtils.createTmpFileWithUTF8Data(
project.getDirPath(),
"_private" + "/" + Base64.encodeBase64URLSafeString(DigestUtils.sha1(dbo.getQName())) + " " + dbo.getName() + "." + JSCRIPT_STEP_EDITOR,
((SimpleStep) dbo).getExpression()
);
studio.createResponse(
new OpenEditableEditorActionResponse(
project.getQName() + "/" + "_private" + "/" + fileName,
JSCRIPT_STEP_EDITOR
).toXml(studio.getDocument(), getObject().getQName())
);
}
catch (Exception e) {
}
}
示例13: sha1
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
public static String sha1(String str){
String s = null;
try {
byte[] data = str.getBytes("UTF-8");
s = DigestUtils.sha1Hex(data);
}catch (Exception ex){
ex.printStackTrace();
}
return s;
}
示例14: createTupasVerificationMac
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
String createTupasVerificationMac(String version, String timestamp, String idNbr, String origStamp,
String custName, String keyVers, String algorithm, String custId,
String custType, String sharedSecret) {
String tupasString = version + "&" + timestamp + "&" + idNbr + "&" + origStamp + "&" +
custName + "&" + keyVers + "&" + algorithm + "&" + custId + "&" + custType + "&" +
sharedSecret + "&";
logger.debug("Generated Tupas response MAC string:\n{}", tupasString);
try {
return DigestUtils.sha256Hex(tupasString.getBytes("ISO-8859-1")).toUpperCase();
} catch (UnsupportedEncodingException e) {
logger.error("Unable to calculate tupas response verification MAC", e);
return null;
}
}
示例15: makeSignBySinpleFieldList
import org.apache.commons.codec.digest.DigestUtils; //导入依赖的package包/类
/**
* 根据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;
}