public String getSecretToken(String nonce) throws OpenRDFException, IOException { if (nonce == null || nonce.length() == 0) throw new BadRequest("Missing nonce"); String uri = this.getResource().stringValue(); String hash = DigestUtils.md5Hex(uri); String secret = this.getRealm().getOriginSecret(); return DigestUtils.md5Hex(hash + ":" + nonce + ":" + secret); }
public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1.获取参数,设置给user对象 */ String loginname = request.getParameter("loginname"); String loginpass = request.getParameter("loginpass"); String reloginpass = request.getParameter("reloginpass"); String email = request.getParameter("email"); Users formUser = new Users(); formUser.setUName(loginname); String md5Digest = DigestUtils.md5Hex(loginpass); formUser.setUPassword(md5Digest); // formUser.setUPassword(loginpass); String md5DigestRepass = DigestUtils.md5Hex(reloginpass); formUser.setReloginpass(md5DigestRepass); formUser.setUEmail(email); /* * 2.校验参数 */ Map<String, String> errors = validateRegist(formUser); if (errors.size() > 0) { request.setAttribute("errors", errors); // 显示错误信息 request.setAttribute("formUser", formUser); // 回显表单信息 return "f:/regist.jsp"; } /* * 3.调用service层方法 */ userService.regist(formUser); return "f:/login.jsp"; // 转发到登录页面 }
/** * Response is calculated using H1 = md5("username:realm:password") H2 = md5("httpmethod:uri") * response = md5("H1:nonce:nc:cnonce:qop:H2") */ private String calculateResponse() throws UnsupportedEncodingException, NoSuchAlgorithmException { String hash_1 = DigestUtils.md5Hex((username + ":" + realm + ":" + password)); String hash_2 = DigestUtils.md5Hex((httpMethod + ":" + uri)); String hash_3_string = hash_1 + ":" + nonce + ":" + nounceCount + ":" + clientNonce + ":" + qop + ":" + hash_2; return DigestUtils.md5Hex(hash_3_string); }
/* * 测试generateSessionId */ @Test public void testGenerateSessionId() throws Exception { String tipSecret = "taobao1234"; dsg.setTipSecret(tipSecret); Class clazz = dsg.getClass(); Method method = clazz.getDeclaredMethod( "generateSessionId", char.class, String.class, String.class, String[].class); method.setAccessible(true); // userId的长度大于等于4位 { String userId = "214637"; String appSecret = "taobao123"; String appkey = "zhenzi"; String[] appkeys = new String[] {appkey}; StringBuilder md5 = new StringBuilder() .append(appSecret) .append(System.currentTimeMillis() / (24 * 60 * 60 * 1000)) .append(appkey) .append(userId) .append(tipSecret); StringBuilder sessionKey = new StringBuilder("2"); sessionKey.append("4637"); sessionKey.append(DigestUtils.md5Hex(md5.toString().getBytes("utf-8"))); String result = (String) method.invoke(dsg, '2', userId, appSecret, appkeys); assertEquals(sessionKey.toString(), result); } // userId的长度小于4位 { String userId = "37"; String appSecret = "taobao123"; String appkey = "zhenzi"; String[] appkeys = new String[] {appkey}; StringBuilder md5 = new StringBuilder() .append(appSecret) .append(System.currentTimeMillis() / (24 * 60 * 60 * 1000)) .append(appkey) .append(userId) .append(tipSecret); StringBuilder sessionKey = new StringBuilder("2"); sessionKey.append("0037"); sessionKey.append(DigestUtils.md5Hex(md5.toString().getBytes("utf-8"))); String result = (String) method.invoke(dsg, '2', userId, appSecret, appkeys); assertEquals(sessionKey.toString(), result); } }
/** * 生成签名 * * @param parameterMap 参数 * @return 签名 */ private String generateSign(Map<String, ?> parameterMap) { PluginConfig pluginConfig = getPluginConfig(); return DigestUtils.md5Hex( joinKeyValue( new TreeMap<String, Object>(parameterMap), null, "&key=" + DigestUtils.md5Hex(pluginConfig.getAttribute("key")), "&", true, "signMethod", "signature")); }
private String buildGravatarUrl() { StringBuilder builder = new StringBuilder(GRAVATAR_URL); builder.append(DigestUtils.md5Hex(email)); builder.append("?size="); builder.append(size); return builder.toString(); }
protected String calculateUaAuthHeader(HttpRequestBase method, Map<String, String> cookies) { final String userAgent = this.getHeaderValue(method, USER_AGENT); final String requestId = this.getHeaderValue(method, RETS_REQUEST_ID); final String sessionId = cookies.get(RETS_SESSION_ID); final String retsVersion = this.getHeaderValue(method, RETS_VERSION); String secretHash = DigestUtils.md5Hex(String.format("%s:%s", userAgent, this.userAgentPassword)); String pieces = String.format( "%s:%s:%s:%s", secretHash, StringUtils.trimToEmpty(requestId), StringUtils.trimToEmpty(sessionId), retsVersion); return String.format("Digest %s", DigestUtils.md5Hex(pieces)); }
/** * MD5加密 * * @param str * @return */ public static String MD5(String str) { if (str != null) { return DigestUtils.md5Hex(str); } else { return null; } }
public void save(Connection connection, String serviceKey, File file) { String sql = " insert into " + BlobItemDomainFactory.TABLENAME + " (ID_, BUSINESSKEY_, FILEID_, SERVICEKEY_, NAME_, TYPE_, FILENAME_, PATH_, LASTMODIFIED_, LOCKED_, STATUS_, DATA_, CREATEBY_, CREATEDATE_)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; PreparedStatement psmt = null; try { psmt = connection.prepareStatement(sql); psmt.setString(1, UUID32.getUUID()); psmt.setString(2, serviceKey); psmt.setString(3, DigestUtils.md5Hex(file.getAbsolutePath())); psmt.setString(4, serviceKey); psmt.setString(5, file.getName()); psmt.setString(6, "Execution"); psmt.setString(7, file.getAbsolutePath()); psmt.setString(8, file.getAbsolutePath()); psmt.setLong(9, file.lastModified()); psmt.setInt(10, 0); psmt.setInt(11, 1); psmt.setBytes(12, FileUtils.getBytes(file)); psmt.setString(13, "system"); psmt.setTimestamp(14, DateUtils.toTimestamp(new java.util.Date())); psmt.executeUpdate(); } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(psmt); } }
@Override public long login( HttpServletRequest request, HttpServletResponse response, String loginName, String pwd, boolean persistent) throws PassportAccountException { loginName = StringUtils.trim(loginName); pwd = StringUtils.trim(pwd); if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(pwd)) { throw new PassportAccountException(PassportAccountException.ACCOUNT_OR_PWD_ERROR); } Passport passport = passportService.getPassportByLoginName(loginName); if (null == passport || !StringUtils.equals(passport.getPassword(), DigestUtils.md5Hex(pwd))) { throw new PassportAccountException(PassportAccountException.ACCOUNT_OR_PWD_ERROR); } Thirdparty tp = null; TpUser tpUser = tpUserService.getTpUserByUid(passport.getId()); if (null != tpUser) { tp = InitData.getTpByTpNameAndJoinType(tpUser.getTpName(), JoinTypeEnum.CONNECT); } doLogin( request, response, passport.getId(), tp != null ? tp.getId() : 0L, RunType.WEB, persistent); nativeLoginCounter.incr(null, 1); return passport.getId(); }
public static String makeFinalParamStringWithSign( String apiId, String messageId, String timestamp, Map<String, Object> params, String secret, String contentKey) { String result = null; if (StringUtils.isNotBlank(apiId) && StringUtils.isNotBlank(messageId) && StringUtils.isNotBlank(timestamp) && StringUtils.isNotBlank(secret)) { Map<String, Object> finalMap = new HashMap<String, Object>(); finalMap.put("ApiId", apiId); finalMap.put("MessageID", messageId); finalMap.put("TimeStamp", timestamp); finalMap.put("Validate", DigestUtils.md5Hex(apiId + secret + timestamp).toUpperCase()); finalMap.putAll(params); ObjectMapper mapper = new ObjectMapper(); try { result = "_data=" + YjBase64Util.encode(mapper.writeValueAsString(finalMap), contentKey); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; }
public RemotePlugin setFile(File f) { try (FileInputStream fis = new FileInputStream(f)) { return this.setFile(f.getName(), DigestUtils.md5Hex(fis)); } catch (IOException e) { throw new IllegalStateException("Fail to compute hash", e); } }
public String shorten(String longUrl, int urlLength) { if (urlLength < 0 || urlLength > 6) { throw new IllegalArgumentException("the length of url must be between 0 and 6"); } String md5Hex = DigestUtils.md5Hex(longUrl); // 6 digit binary can indicate 62 letter & number from 0-9a-zA-Z int binaryLength = urlLength * 6; long binaryLengthFixer = Long.valueOf(StringUtils.repeat("1", binaryLength), BINARY); for (int i = 0; i < 4; i++) { String subString = StringUtils.substring(md5Hex, i * 8, (i + 1) * 8); subString = Long.toBinaryString(Long.valueOf(subString, 16) & binaryLengthFixer); subString = StringUtils.leftPad(subString, binaryLength, "0"); StringBuilder sbBuilder = new StringBuilder(); for (int j = 0; j < urlLength; j++) { String subString2 = StringUtils.substring(subString, j * 6, (j + 1) * 6); int charIndex = Integer.valueOf(subString2, BINARY) & NUMBER_61; sbBuilder.append(DIGITS[charIndex]); } String shortUrl = sbBuilder.toString(); if (lookupLong(shortUrl) != null) { continue; } else { return shortUrl; } } // if all 4 possibilities are already exists return null; }
/** * Returns a hash that should be consistent for any individual swarm client (as long as it has a * persistent IP) and should be unique to that client. * * @param remoteFsRoot the file system root should be part of the hash (to support multiple swarm * clients from the same machine) * @return our best effort at a consistent hash */ public static String hash(File remoteFsRoot) { StringBuilder buf = new StringBuilder(); try { buf.append(remoteFsRoot.getCanonicalPath()).append('\n'); } catch (IOException e) { buf.append(remoteFsRoot.getAbsolutePath()).append('\n'); } try { for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) { for (InetAddress ia : Collections.list(ni.getInetAddresses())) { if (ia instanceof Inet4Address) { buf.append(ia.getHostAddress()).append('\n'); } else if (ia instanceof Inet6Address) { buf.append(ia.getHostAddress()).append('\n'); } } byte[] hardwareAddress = ni.getHardwareAddress(); if (hardwareAddress != null) { buf.append(Arrays.toString(hardwareAddress)); } } } catch (SocketException e) { // oh well we tried } return DigestUtils.md5Hex(buf.toString()).substring(0, 8); }
/** * 增加一个新节点 @Title: addCacheNode * * @author: zzh * @date: 2016年12月2日 下午8:56:38 * @version: v1.0.0 */ private static void addCacheNode() { // 添加到真实Node列表 CacheNode newNode = new CacheNode("10.9.1.100"); realNodeList.add(newNode); // 生成虚拟节点 List<VisualCacheNode> addVisualNodeList = genVisualCacheNode(newNode); // 查询哪些节点受到影响,即数据需要分散 for (VisualCacheNode vnode : addVisualNodeList) { String nodeName = vnode.getNodeName(); String md5VisualNodeKey = DigestUtils.md5Hex(nodeName); // 使用common-codec工具包 int hashNodeName = DJBHash(md5VisualNodeKey); SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName + 1); // 排除掉自己。 VisualCacheNode nodeInfo = null; if (vs != null && vs.size() > 0) { int affectVnshash = vs.firstKey(); nodeInfo = visualNodeMap.get(affectVnshash); } else { nodeInfo = visualNodeMap.get(visualNodeMap.firstKey()); } System.out.println("新添节点,受到影响的虚拟节点:" + nodeInfo); } // 将虚拟节点加入到hash环中 addVisualCacheNodeIntoCircle(addVisualNodeList); }
@Override public void save(EditableModel obj) throws DaoException { ExternalApp externalApp = (ExternalApp) obj; externalApp.setAppId(createAppId()); externalApp.setThreeDesKey(getUUID()); externalApp.setCreateTime(new Date()); externalApp.setUpdateTime(externalApp.getCreateTime()); User user = new User(); user.setUserName(externalApp.getAppName()); user.setPassword(DigestUtils.md5Hex(SystemConfig.getString("system.user.default-password"))); user.setCreateTime(new Date()); user.setUpdateTime(user.getCreateTime()); user.setState(Constants.FLAG_USER_STATE_USING.value()); user.setType(Constants.FLAG_USER_TYPE_APPUSER.value()); try { userDao.save(user); User newUser = userDao.queryByUserName(user.getUserName()); externalApp.setUser(newUser); externalAppDao.save(externalApp); } catch (Exception e) { LogUtil.error(this, "ExternalAppServiceImpl.save error", e); throw new DaoException(e); } }
/** * 删除节点。 @Title: removeCacheNode * * @author: zzh * @date: 2016年12月4日 下午8:34:15 * @version: v1.0.0 */ private static void removeCacheNode(String nodeIp) { // 删除当前IP的虚拟节点信息 CacheNode cacheNode = new CacheNode(nodeIp); // 获取当前节点的虚拟节点信息 List<VisualCacheNode> vNodesList = genVisualCacheNode(cacheNode); // 从hash环中删除虚拟节点信息 for (VisualCacheNode c : vNodesList) { String vNodeName = c.getNodeName(); String md5VisualNodeKey = DigestUtils.md5Hex(vNodeName); // 使用common-codec工具包 int hashNodeName = DJBHash(md5VisualNodeKey); visualNodeMap.remove(hashNodeName); System.out.println("删除虚拟节点,虚拟节点名称:" + vNodeName + ",真实节点:" + c.getRealCacheNode()); // 删除后,受到影响的节点:即数据和流量需要迁移到的节点信息 SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName); VisualCacheNode nodeInfo = null; if (vs != null && vs.size() > 0) { int affectVnshash = vs.firstKey(); nodeInfo = visualNodeMap.get(affectVnshash); } else { nodeInfo = visualNodeMap.get(visualNodeMap.firstKey()); } System.out.println("删除当前虚拟节点" + vNodeName + " , 受到影响的虚拟节点(原本虚拟节点的数据和流量将迁移到此节点):" + nodeInfo); } // 踢出真实节点 removeRealCache(nodeIp); }
/** * 随机初始化一部分数据分散到虚拟节点上 @Title: initRadomData2VisualNode * * @author: zzh * @date: 2016年12月1日 下午7:59:23 * @version: v1.0.0 */ private static void initRadomData2VisualNode() { for (int i = 0; i < 100; i++) { String dataKey = DigestUtils.md5Hex(new Random(System.nanoTime()).nextInt() + ""); VisualCacheNode nearestCacheNode = getVisualCacheNode(dataKey); // 将key值和真实缓存节点的关联关系存储起来 dataCache.put(dataKey, nearestCacheNode.getRealCacheNode()); // 补充当前节点上存储的key值信息 List<String> keyList = vNodeCacheDataMap.get(nearestCacheNode.getNodeName()); if (keyList == null) { keyList = new ArrayList<String>(); } keyList.add(dataKey); vNodeCacheDataMap.put(nearestCacheNode.getNodeName(), keyList); System.out.println( "当前测试数据key=" + dataKey + ",使用虚拟节点:" + nearestCacheNode.getNodeName() + ",真实Cache节点:" + nearestCacheNode.getRealCacheNode().getNodeName()); } }
public static String md5Checksum(File file) { try { return DigestUtils.md5Hex(new FileInputStream(file)); } catch (IOException ioe) { throw new CLIException(REASON_IO_ERROR, ioe); } }
@Test public void testMD5() { String str = "app_id=1814810&buy_amount=10&cp_order_id=mt_meizu_7337605_1398766447_1&create_time=1398766520051¬ify_id=1398766589010¬ify_time=2014-04-29 18:16:29&order_id=14042900000000044&partner_id=0&pay_time=1398766589036&product_id=pid_meizu_7337605_1398766447_1&product_per_price=0.1&product_unit=gold&total_price=1.0&trade_status=3"; str += (":" + "eSikRwObIpkg9Bmt3ty1R8CJf4nlE5bL"); System.out.println(DigestUtils.md5Hex(str)); }
public static String md5checkSum(File file) throws IOException { String checksum = null; FileInputStream fis = new FileInputStream(file); checksum = DigestUtils.md5Hex(fis); fis.close(); return checksum; }
private File getCachedImage(File file, int size) throws IOException { String md5 = DigestUtils.md5Hex(file.getPath()); File cachedImage = new File(getImageCacheDirectory(size), md5 + ".jpeg"); // Is cache missing or obsolete? if (!cachedImage.exists() || FileUtil.lastModified(file) > cachedImage.lastModified()) { InputStream in = null; OutputStream out = null; try { in = getImageInputStream(file); out = new FileOutputStream(cachedImage); BufferedImage image = ImageIO.read(in); if (image == null) { throw new Exception("Unable to decode image."); } image = scale(image, size, size); ImageIO.write(image, "jpeg", out); } catch (Throwable x) { // Delete corrupt (probably empty) thumbnail cache. LOG.warn("Failed to create thumbnail for " + file, x); IOUtils.closeQuietly(out); cachedImage.delete(); throw new IOException("Failed to create thumbnail for " + file + ". " + x.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } return cachedImage; }
/** * 构造package, 这是我见到的最草蛋的加密,尼玛文档还有错 * * @param params * @param paternerKey * @return * @throws UnsupportedEncodingException */ private static String packageSign(Map<String, String> params, String paternerKey) throws UnsupportedEncodingException { String string1 = createSign(params, false); String stringSignTemp = string1 + "&key=" + paternerKey; String signValue = DigestUtils.md5Hex(stringSignTemp).toUpperCase(); String string2 = createSign(params, true); return string2 + "&sign=" + signValue; }
/** * Validate the provided trust token. * * @param token : The token to validate * @return boolean : True if the token is valid, False otherwise */ @Override public boolean testTrustToken(JsonSessionState session, String token) { String[] parts = StringUtils.split(token, ":"); // Check the length if (parts.length != 4) { log.error("TOKEN: Should have 4 parts, not {} : '{}'", parts.length, token); return false; } // Check the parts String username = parts[0]; String timestamp = parts[1]; String publicKey = parts[2]; String userToken = parts[3]; if (username.isEmpty() || timestamp.isEmpty() || publicKey.isEmpty() || userToken.isEmpty()) { log.error("TOKEN: One or more parts are empty : '{}'", token); return false; } // Make sure the publicKey is valid if (!tokens.containsKey(publicKey)) { log.error("TOKEN: Invalid public key : '{}'", publicKey); return false; } String privateKey = tokens.get(publicKey); Long expiry = tokenExpiry.get(publicKey); // Check for valid timestamp & expiry timestamp = getFormattedTime(timestamp); if (timestamp == null) { log.error("TOKEN: Invalid timestamp : '{}'", timestamp); return false; } Long tokenTime = Long.valueOf(timestamp); Long currentTime = Long.valueOf(getFormattedTime(null)); Long age = currentTime - tokenTime; if (age > expiry) { log.error("Token is passed its expiry : {}s old", age); return false; } // Now validate the token itself String tokenSeed = username + ":" + timestamp + ":" + privateKey; String expectedToken = DigestUtils.md5Hex(tokenSeed); if (userToken.equals(expectedToken)) { // The token is valid session.set("username", username); session.set("source", TRUST_TOKEN_PREFIX + publicKey); // Store it in case we redirect later session.set("validToken", token); return true; } // Token was not valid log.error("TOKEN: Invalid token, hash does not match: '{}'", userToken); return false; }
/** * 签名字符串 * * @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; } }
/** Returns the Gravatar URL for the given email address. */ public String getUrl(String email) { Validate.notNull(email, "email"); // hexadecimal MD5 hash of the requested user's lowercased email address // with all whitespace trimmed String emailHash = DigestUtils.md5Hex(email.toLowerCase().trim()); String params = formatUrlParameters(); return GRAVATAR_URL + emailHash + ".jpg" + params; }
public TnrsJobRequest( String email, String inputFile, String original_filename, boolean email_results) throws Exception { this.email = email; this.filename = inputFile; id = DigestUtils.md5Hex(email + inputFile); original = original_filename; emailResults = email_results; }
@Test public void testKfAccountAddAction() throws ValidateException { ActionMulticaster multicaster = Context.getContext().getBean(ActionMulticaster.class); KfAccountAddReq req = new KfAccountAddReq(); req.setKfAccount("test@gh_ed595887caa3"); req.setNickname("客服"); req.setPassword(DigestUtils.md5Hex("123456q")); BaseRes res = multicaster.multicast(req); System.out.println(JSON.toJSONString(res)); }
/** * 生成文件摘要 * * @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 ""; } }
/** * Returns the filter decision * * @param message - the message content * @return */ public boolean filter(String message, String filterCondition) { Date dt = new Date(); long currentTime = dt.getTime(); String digest = DigestUtils.md5Hex(message); Long lastTime = digestDB.get(digest); if (lastTime == null) return true; long per = currentTime - lastTime.longValue(); if (per > getPeriod(filterCondition)) return true; else return false; }