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

The following are Jave code examples for showing how to use md5Hex() 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: take   File: TakeTest.java   View Source Code Vote up 6 votes
@Test
public void test02() throws Exception {
    HttpUrl parse = HttpUrl.parse("http://www.dapenti.com/blog/more.asp?name=xilei&id=123093");
    System.out.println(parse);
    System.out.println(parse.host());

    System.out.println(parse.uri());
    System.out.println(parse.encodedPath());
    System.out.println(parse.encodedQuery());
    System.out.println(parse.query());


    String s = DigestUtils.md5Hex(parse.toString());
    String s2 = DigestUtils.md5Hex(parse.toString());
    System.out.println(s);
    System.out.println(s2);
}
 
Example 2
Project: s3-inventory-usage-examples   File: InventoryManifestRetriever.java   View Source Code Vote up 6 votes
/**
 * Check if the MD5s of manifest.json and manifest.checksum equal
 * if so, pull out the manifest file and map it into a POJO
 * @return inventoryManifestStorage InventoryManifest, which stores all the elements of the manifest.json file
 */
public InventoryManifest getInventoryManifest() throws Exception {
    // Get manifest.json and transfer it to String
    GetObjectRequest requestJson = new GetObjectRequest(bucketName, bucketKeyJson);
    S3Object jsonObject = s3Client.getObject(requestJson);
    String jsonFile = inputStreamToString(jsonObject.getObjectContent());
    jsonObject.close();

    // Get manifest.checksum and transfer it to String with no whitespace
    GetObjectRequest requestChecksum = new GetObjectRequest(bucketName, bucketKeyChecksum);
    S3Object checksumObject = s3Client.getObject(requestChecksum);
    String expectedChecksum = inputStreamToString(checksumObject.getObjectContent())
            .replaceAll("\\s","");
    checksumObject.close();

    // Compare manifest.json and manifest.checksum's MD5 value
    String actualChecksum = DigestUtils.md5Hex(jsonFile);
    if (!actualChecksum.equals(expectedChecksum)) {
        throw new ChecksumMismatchException (expectedChecksum, actualChecksum);
    }

    return mapper.readValue(jsonFile, InventoryManifest.class);
}
 
Example 3
Project: crawler   File: RedisScheduler.java   View Source Code Vote up 6 votes
@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();
	        }
	}
   }
 
Example 4
Project: wakeup-qcloud-sdk   File: QCloudStreamUrlUtil.java   View Source Code Vote up 6 votes
/**
 * 获取推流地址 如果不传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;
}
 
Example 5
Project: k-framework   File: AlipayCore.java   View Source Code Vote up 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 6
Project: cyberduck   File: DefaultTemporaryFileServiceTest.java   View Source Code Vote up 5 votes
@Test
public void testPathTooLong() {
    final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator);
    final String testPathDirectory = "/Lorem/ipsum/dolor/sit/amet/consetetur/sadipscing/elitr/sed/diam/nonumy/eirmod/tempor/invidunt/ut/labore/et/dolore/magna/aliquyam/erat/sed/diam/voluptua/At/vero/eos/et/accusam/et/justo/duo/dolores/et/ea/rebum/Stet/clita/kasd/gubergren/no/sea";
    final String testPathFile = "takimata.sanc";
    final String testPath = String.format("%s/%s", testPathDirectory, testPathFile);
    final String testPathMD5 = DigestUtils.md5Hex(testPathDirectory);

    final Path file = new Path(testPath, EnumSet.of(Path.Type.file));
    file.attributes().setVersionId("2");
    final Local local = new DefaultTemporaryFileService().create("UID", file);
    final String localFile = local.getAbsolute();
    assertNotEquals(String.format("%s/%s%s/2/%s", temp, "UID", testPathDirectory, testPathFile).replace('/', File.separatorChar), localFile);
    assertEquals(String.format("%s/%s/%s/2/%s", temp, "UID", testPathMD5, testPathFile).replace('/', File.separatorChar), localFile);
}
 
Example 7
Project: BilibiliAccessKey   File: BilibiliAccessKey.java   View Source Code Vote up 5 votes
private static String getSign(Map<String, String> params, String appKey, String appSecret) throws UnsupportedEncodingException {
    TreeMap<String, String> paramsSorted = new TreeMap<>(params);
    String data = "";
    paramsSorted.put("appkey", appKey);
    for (String key : paramsSorted.keySet()) {
        if (data != "")
            data += "&";
        data += key + "=" + urlEncode(paramsSorted.get(key));
    }
    if (appSecret == null)
        return data;
    return data + "&sign=" + DigestUtils.md5Hex(data + appSecret);
}
 
Example 8
Project: framework   File: AlipayCore.java   View Source Code Vote up 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 9
Project: framework   File: MD5.java   View Source Code Vote up 5 votes
/**
 * 签名字符串
 *
 * @param text          需要签名的字符串
 * @param sign          签名结果
 * @param key           密钥
 * @param input_charset 编码格式
 * @return 签名结果
 */
public static boolean verify(String text, String sign, String key, String input_charset) {
	text = text + key;
	String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
	if (mysign.equals(sign)) {
		return true;
	} else {
		return false;
	}
}
 
Example 10
Project: cas-5.1.0   File: DigestAuthenticationUtils.java   View Source Code Vote up 5 votes
/**
 * Create nonce string.
 *
 * @return the nonce
 */
public static String createNonce() {
    final String fmtDate = ZonedDateTime.now().toString();
    final SecureRandom rand = new SecureRandom();
    final Integer randomInt = rand.nextInt();
    return DigestUtils.md5Hex(fmtDate + randomInt);
}
 
Example 11
Project: raven   File: IOSFilecast.java   View Source Code Vote up 5 votes
public String uploadContents(String contents) throws Exception {
	if (!rootJson.has("appkey") || !rootJson.has("timestamp")) {
		throw new Exception("appkey, timestamp and validation_token needs to be set.");
	}
	// Construct the json string
	JSONObject uploadJson = new JSONObject();
	uploadJson.put("appkey", rootJson.getString("appkey"));
	uploadJson.put("timestamp", rootJson.getString("timestamp"));
	uploadJson.put("content", contents);
	// Construct the request
	String url = host + uploadPath;
	String postBody = uploadJson.toString();
	String sign = DigestUtils.md5Hex("POST" + url + postBody + appMasterSecret);
	url = url + "?sign=" + sign;
	HttpPost post = new HttpPost(url);
	post.setHeader("User-Agent", USER_AGENT);
	StringEntity se = new StringEntity(postBody, "UTF-8");
	post.setEntity(se);
	// Send the post request and get the response
	HttpResponse response = client.execute(post);
	System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
	BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	StringBuffer result = new StringBuffer();
	String line = "";
	while ((line = rd.readLine()) != null) {
		result.append(line);
	}
	System.out.println(result.toString());
	// Decode response string and get file_id from it
	JSONObject respJson = new JSONObject(result.toString());
	String ret = respJson.getString("ret");
	if (!ret.equals("SUCCESS")) {
		throw new Exception("Failed to upload file");
	}
	JSONObject data = respJson.getJSONObject("data");
	String fileId = data.getString("file_id");
	// Set file_id into rootJson using setPredefinedKeyValue
	setPredefinedKeyValue("file_id", fileId);
	return fileId;
}
 
Example 12
Project: WeiXing_xmu-2016-MrCode   File: MD5.java   View Source Code Vote up 5 votes
/**
 * 签名字符串
 * @param text 需要签名的字符串
 * @param sign 签名结果
 * @param key 密钥
 * @param input_charset 编码格式
 * @return 签名结果
 */
public static boolean verify(String text, String sign, String key, String input_charset) {
	text = text + key;
	String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
	if(mysign.equals(sign)) {
		return true;
	}
	else {
		return false;
	}
}
 
Example 13
Project: gitplex-mit   File: AvatarGenerator.java   View Source Code Vote up 4 votes
private static Long getColorIndex(String email) throws NoSuchAlgorithmException {
	String hex = DigestUtils.md5Hex(email);
	return Long.parseLong(hex.substring(0, 15), 16) % COLORS.length;
}
 
Example 14
Project: soapbox-race-core   File: AccoladesFunc.java   View Source Code Vote up 4 votes
public LuckyDrawItem getItemFromProduct(Integer rank, Integer level, Boolean isTH) {
	Integer hash = 0, count = 0, price = 0;
	String desc = "", icon = "", vItem = "", vItemType = "";
	Boolean isSold = false;
	
	List<ProductEntity> getProductItems = null;
	
	Integer randomCategory = getRandomCat(rank, isTH, new Random().nextInt(10));
	if(randomCategory == 1) { // Powerup
		getProductItems = productDao.findForEndRace("STORE_POWERUPS", "POWERUP", level);
	} else if(randomCategory == 2) { // Perf
		getProductItems = productDao.findForEndRace("NFSW_NA_EP_PERFORMANCEPARTS", "PERFORMANCEPART", level);
	} else if(randomCategory == 3) { // Skill
		getProductItems = productDao.findForEndRace("NFSW_NA_EP_SKILLMODPARTS", "SKILLMODPART", level);
	} else if(randomCategory == 4) { // Visual
		getProductItems = productDao.findForEndRace(getVisualCatgeory(new Random().nextInt(8)), "VISUALPART", level);
	}
	
	if(getProductItems != null) { // Other part
		Integer randomDrop = new Random().nextInt(getProductItems.size());
		ProductEntity productEntity = getProductItems.get(randomDrop);
		
		if(randomCategory == 1) {
			String strCut = productEntity.getProductTitle().replace("x15", "");
			count = new Random().nextInt(15) + 1;
			desc = strCut + " x" + count;
		} else {
			desc = productEntity.getProductTitle();
			count = 1;
		}
		hash = productEntity.getHash().intValue();
		icon = productEntity.getIcon();
		price = (int)(productEntity.getPrice() / 3.5);
		vItem = DigestUtils.md5Hex(productEntity.getHash().toString());
		vItemType = productEntity.getProductType();
	} else { // Cash part
		Integer cashBonus = new Random().nextInt(25000) + 1;
		desc = String.valueOf(cashBonus) + " CASH";
		icon = "128_cash";
		vItemType = "CASH";
	}
	
	LuckyDrawItem luckyDrawItem = new LuckyDrawItem();
	luckyDrawItem.setDescription(desc);
	luckyDrawItem.setHash(hash);
	luckyDrawItem.setIcon(icon);
	luckyDrawItem.setRemainingUseCount(count);
	luckyDrawItem.setResellPrice(price);
	luckyDrawItem.setVirtualItem(vItem);
	luckyDrawItem.setVirtualItemType(vItemType);
	luckyDrawItem.setWasSold(isSold);
	return luckyDrawItem;
}
 
Example 15
Project: JahiaDF   File: PageContentModelToJSONServlet.java   View Source Code Vote up 4 votes
@Override
public ActionResult doExecute(HttpServletRequest request, RenderContext renderContext, Resource resource,
                              JCRSessionWrapper session, Map<String, List<String>> parameters,
                              URLResolver urlResolver) throws Exception {

    JSONObject filteredContentMap = new JSONObject();
    final HttpServletResponse response = renderContext.getResponse();

    try {
        View view = null;
        if ( resource.getNode() != null && resource.getNode().getPrimaryNodeType() != null &&
                StringUtils.startsWithAny(resource.getNode().getPrimaryNodeType().getName(),
                        LIST_TEMPLATE_OPTION_TYPES) ){
            view = JahiaUtils.resolveTemplateResourceView(request, resource, renderContext);
            // Set view in the request since the view is needed by the contentModelFactoryService service
            request.setAttribute(JAHIA_SCRIPT_VIEW, view);
        }
        if (view != null) {
            TemplateContentModel templateContentModel = (TemplateContentModel)
                    contentModelFactoryService.getContentModel(request, response, renderContext, resource);

            boolean clientAccessible =
                    (Boolean) templateContentModel.get(CONFIG_PROPERTIES_KEY + DOT + XK_CLIENT_ACCESSIBLE_CP);

            if (clientAccessible) {
                // get list of contexts
                Configuration configuration = configurationProvider.getFor(view);

                Collection<String> props = configuration.asStrings(XK_CLIENT_MODEL_PROPERTIES_CP, Mode.MERGE);
                String[] contexts = props.toArray(new String[0]);

                // get content model json with the XK_CLIENT_MODEL_PROPERTIES_CP contexts
                filteredContentMap = templateContentModel.toJSONObject(contexts);

                // add component id
                String componentContentId = DigestUtils.md5Hex(resource.getPath());
                filteredContentMap.put(XK_CONTENT_ID_CP, componentContentId);
            }

            // add component list with clientaccessible as true on the resource page
            filteredContentMap.put(PAGE_COMPONENT_RESOURCE_LIST_AN, getComponentList(
                    resource, request, response, renderContext));
        }
    } catch (Exception ew) {

        throw new ServletException(ew);
    }

    response.setContentType(SERVER_RESPONSE_CONTENT_TYPE);
    response.getWriter().write( filteredContentMap.toString() );

    return ActionResult.OK;
}
 
Example 16
Project: Spring-Boot-Server   File: AppUserLoginRestful.java   View Source Code Vote up 4 votes
/**
 * UUID注册
 * 
 * @return
 */
@RequestMapping(value = "/registerUUID")
@ResponseBody
public PageData registerUUID(@RequestBody PageData pd) {
	try {
		// 1.生成UUID,状态为0,失效时间10分钟
		// TYPE 盒子类型 0公网盒子1 IPTV盒子
		// OPERATOR 运营商(iptv) 0移动 1联通 2电信

		String UUID = pd.getString("uuid");
		String TYPE = pd.getString("type");
		String OPERATOR = pd.getString("operator");
		String MAC = pd.getString("mac");

		if (StringUtils.isNotBlank(UUID) && StringUtils.isNotBlank(TYPE) && StringUtils.isNotBlank(OPERATOR)) {
			String md5=DigestUtils.md5Hex(UUID);
			String redisUUID = String.join("", redisKeyPre,md5);
			ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue();
			if (!redisTemplate.hasKey(redisUUID)) {
				// 存储到redis 缓存,十分钟有效
				PageData map = new PageData();
				map.put("type", TYPE);
				map.put("operator", OPERATOR);
				map.put("mac", MAC);
				map.put("UUID", UUID);
				map.put("option", "0");
				redisOpt.set(redisUUID, map, redisTimeout, TimeUnit.SECONDS);
				PageData retPd=new PageData();
				retPd.put("signature", md5);
				return WebResult.requestSuccess(retPd);
			} else {
				return WebResult.requestFailed(500, String.join("", UUID, "已存在"), null);
			}
		} else {
			return WebResult.requestFailed(500, "参数不正确", null);
		}
	} catch (Exception e) {
		e.printStackTrace();
		return WebResult.requestFailed(400, "参数不正确", null);
	}
}
 
Example 17
Project: obevo   File: OldWhitespaceAgnosticDbChangeHashStrategy.java   View Source Code Vote up 4 votes
@Override
public String hashContent(String content) {
    return DigestUtils.md5Hex(this.normalizeFileContentsForHashing(content));
}
 
Example 18
Project: simple-sso   File: MD5Util.java   View Source Code Vote up 2 votes
/**
 * MD5加密字符串
 * 
 * @param src
 * @return
 */
public static String encode(String src) {
	return DigestUtils.md5Hex(src);
}
 
Example 19
Project: weixinpay   File: MD5.java   View Source Code Vote up 2 votes
/**
 * 签名字符串
 * @param text 需要签名的字符串
 * @param sign 签名结果
 * @param key 密钥
 * @param input_charset 编码格式
 * @return 签名结果
 */
public static boolean verify(String text, String sign, String key, String input_charset) {
	text = text + key;
	String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
    return mysign.equals(sign);
}
 
Example 20
Project: framework   File: MD5.java   View Source Code Vote up 2 votes
/**
 * 签名字符串
 *
 * @param text          需要签名的字符串
 * @param key           密钥
 * @param input_charset 编码格式
 * @return 签名结果
 */
public static String sign(String text, String key, String input_charset) {
	text = text + key;
	return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}