當前位置: 首頁>>代碼示例>>Java>>正文


Java DigestUtils類代碼示例

本文整理匯總了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() + "'");
    }
}
 
開發者ID:differentway,項目名稱:couchmove,代碼行數:27,代碼來源:FileUtils.java

示例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();
}
 
開發者ID:GoldRenard,項目名稱:JuniperBotJ,代碼行數:29,代碼來源:BlurImageController.java

示例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);//比較
}
 
開發者ID:pandboy,項目名稱:pingguopai,代碼行數:28,代碼來源:WebMvcConfigurer.java

示例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);
  }

}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:25,代碼來源:CronJob.java

示例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());
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:19,代碼來源:Signs.java

示例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());
}
 
開發者ID:ProgrammingLife2017,項目名稱:hygene,代碼行數:13,代碼來源:FileMetadata.java

示例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();
        }
}
 
開發者ID:doubleview,項目名稱:fastcrawler,代碼行數:19,代碼來源:FileResultHandler.java

示例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;
}
 
開發者ID:arcuri82,項目名稱:testing_security_development_enterprise_systems,代碼行數:38,代碼來源:UserEJB.java

示例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 "";
	}
}
 
開發者ID:funtl,項目名稱:framework,代碼行數:18,代碼來源:AlipayCore.java

示例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;
}
 
開發者ID:51wakeup,項目名稱:wakeup-qcloud-sdk,代碼行數:19,代碼來源:QCloudStreamUrlUtil.java

示例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();
	        }
	}
   }
 
開發者ID:xbynet,項目名稱:crawler,代碼行數:17,代碼來源:RedisScheduler.java

示例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) {
    }
}
 
開發者ID:convertigo,項目名稱:convertigo-engine,代碼行數:23,代碼來源:StepView.java

示例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;
}
 
開發者ID:noear,項目名稱:JtSQL,代碼行數:13,代碼來源:EncryptUtil.java

示例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;
    }
}
 
開發者ID:vrk-kpa,項目名稱:e-identification-tupas-idp-public,代碼行數:17,代碼來源:SessionParserService.java

示例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;

}
 
開發者ID:minlia-projects,項目名稱:minlia-iot,代碼行數:79,代碼來源:XmlSignatureAnnotationHelper.java


注:本文中的org.apache.commons.codec.digest.DigestUtils類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。