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

The following are Jave code examples for showing how to use sha1Hex() 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: 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 2
Project: JtSQL   File: EncryptUtil.java   View Source Code Vote up 6 votes
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;
}
 
Example 3
Project: convertigo-engine   File: MinificationManager.java   View Source Code Vote up 6 votes
private ResourceBundle(ResourceType resourceType, File virtualFile, String key) {
	this.resourceType= resourceType; 
	this.virtualFile = virtualFile;
	key = key.replaceFirst("(.*?)/_private/(?:flashupdate|mobile)/", "$1/DisplayObjects/mobile/");
	key = DigestUtils.md5Hex(key) + DigestUtils.sha1Hex(key) + "." + resourceType.name();
	cacheFile = new File(minificationCacheDirectory, key);
}
 
Example 4
Project: soapbox-race-core   File: PromoCodeBO.java   View Source Code Vote up 6 votes
private UserEntity checkLogin(String email, String password) {
	password = (DigestUtils.sha1Hex(password));
	if (email != null && !email.isEmpty() && !password.isEmpty()) {
		UserEntity userEntity = userDao.findByEmail(email);
		if (userEntity != null) {
			if (password.equals(userEntity.getPassword())) {
				return userEntity;
			}
		}
	}
	return null;
}
 
Example 5
Project: Wechat-Group   File: SHA1.java   View Source Code Vote up 6 votes
/**
 * 用&串接arr参数,生成sha1 digest
 */
public static String genWithAmple(String... arr) {
  Arrays.sort(arr);
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < arr.length; i++) {
    String a = arr[i];
    sb.append(a);
    if (i != arr.length - 1) {
      sb.append('&');
    }
  }
  return DigestUtils.sha1Hex(sb.toString());
}
 
Example 6
Project: ymate-payment-v2   File: WxPayJsApiController.java   View Source Code Vote up 6 votes
private String __buildJsApiConfigStr(String appId, String jsapiTicket, String url, String timestamp, String noncestr, boolean debug) throws Exception {
    String _signature = "jsapi_ticket=" + jsapiTicket + "&" + "noncestr=" + noncestr + "&" + "timeStamp=" + timestamp + "&" + "url=" + url;
    _signature = DigestUtils.sha1Hex(_signature);
    //
    JSONObject _json = new JSONObject();
    _json.put("debug", debug);
    _json.put("appId", appId);
    _json.put("timestamp", timestamp);
    _json.put("nonceStr", noncestr);
    _json.put("signature", _signature);
    _json.put("jsApiList", new String[]{"chooseWXPay"});
    //
    return _json.toJSONString();
}
 
Example 7
Project: JuniperBotJ   File: BlurImageController.java   View Source Code Vote up 6 votes
@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();
}
 
Example 8
Project: alerts-forwarder   File: AppUtils.java   View Source Code Vote up 6 votes
public static String generateUniqueId(String metrics) {    // 相同的metrics定会产生相同的uniqueID
	String metricsID = DigestUtils.sha1Hex(metrics + atomicInteger.incrementAndGet());    // 40个字符组成
	char[] _chars = metricsID.toCharArray();
	StringBuilder sb = new StringBuilder();
	for(int i = 0; i < _chars.length; i ++ ) {
		if(i % 10 == 0 && i != 0) {	// 10、20和30
			sb.append("-");
		}
		sb.append(String.valueOf(_chars[i]));
	}
	
	return sb.toString();
}
 
Example 9
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 10
Project: Backmemed   File: ResourcePackRepository.java   View Source Code Vote up 6 votes
private boolean checkHash(String p_190113_1_, File p_190113_2_)
{
    try
    {
        String s = DigestUtils.sha1Hex((InputStream)(new FileInputStream(p_190113_2_)));

        if (p_190113_1_.isEmpty())
        {
            LOGGER.info("Found file {} without verification hash", new Object[] {p_190113_2_});
            return true;
        }

        if (s.toLowerCase(java.util.Locale.ROOT).equals(p_190113_1_.toLowerCase(java.util.Locale.ROOT)))
        {
            LOGGER.info("Found file {} matching requested hash {}", new Object[] {p_190113_2_, p_190113_1_});
            return true;
        }

        LOGGER.warn("File {} had wrong hash (expected {}, found {}).", new Object[] {p_190113_2_, p_190113_1_, s});
    }
    catch (IOException ioexception)
    {
        LOGGER.warn("File {} couldn\'t be hashed.", new Object[] {p_190113_2_, ioexception});
    }

    return false;
}
 
Example 11
Project: CustomWorldGen   File: ResourcePackRepository.java   View Source Code Vote up 6 votes
private boolean checkHash(String p_190113_1_, File p_190113_2_)
{
    try
    {
        String s = DigestUtils.sha1Hex((InputStream)(new FileInputStream(p_190113_2_)));

        if (p_190113_1_.isEmpty())
        {
            LOGGER.info("Found file {} without verification hash", new Object[] {p_190113_2_});
            return true;
        }

        if (s.toLowerCase().equals(p_190113_1_.toLowerCase()))
        {
            LOGGER.info("Found file {} matching requested hash {}", new Object[] {p_190113_2_, p_190113_1_});
            return true;
        }

        LOGGER.warn("File {} had wrong hash (expected {}, found {}).", new Object[] {p_190113_2_, p_190113_1_, s});
    }
    catch (IOException ioexception)
    {
        LOGGER.warn("File {} couldn\'t be hashed.", new Object[] {p_190113_2_, ioexception});
    }

    return false;
}
 
Example 12
Project: garlicts   File: CodecUtil.java   View Source Code Vote up 5 votes
/**
 * 将字符串 SHA 加密
 */
public static String encryptSHA(String str) {
    return DigestUtils.sha1Hex(str);
}
 
Example 13
Project: soapbox-race-jlauncher   File: UserVO.java   View Source Code Vote up 5 votes
public UserVO(String email, String password) {
	this.email = email;
	this.password = password;
	this.shaPassword = DigestUtils.sha1Hex(password);
}
 
Example 14
Project: GodotFireBase   File: Notification.java   View Source Code Vote up 5 votes
public void sendMessage (final String data) {
	FirebaseMessaging fm = FirebaseMessaging.getInstance();

	String token = FirebaseInstanceId.getInstance().getToken();
	String msgID = DigestUtils.sha1Hex(token + System.currentTimeMillis());
	String SENDER_ID = "someID";

	RemoteMessage.Builder RMBuilder =
	new RemoteMessage.Builder(SENDER_ID + "@gcm.googleapis.com");
	RMBuilder.setMessageId(msgID);

	Map<String, Object> mapData = Utils.jsonToMap(data);

	for (Map.Entry<String, Object> entry : mapData.entrySet()) {
		RMBuilder.addData(entry.getKey(), entry.getValue().toString());
	}

	fm.send(RMBuilder.build());
}
 
Example 15
Project: cos-java-sdk-v5   File: COSSigner.java   View Source Code Vote up 5 votes
public String buildAuthorizationStr(HttpMethodName methodName, String resouce_path,
        Map<String, String> headerMap, Map<String, String> paramMap, COSCredentials cred,
        Date expiredTime) {

    if (isAnonymous(cred)) {
        return null;
    }

    Map<String, String> signHeaders = buildSignHeaders(headerMap);
    // 签名中的参数和http 头部 都要进行字符串排序
    TreeMap<String, String> sortedSignHeaders = new TreeMap<>();
    TreeMap<String, String> sortedParams = new TreeMap<>();

    sortedSignHeaders.putAll(signHeaders);
    sortedParams.putAll(paramMap);

    String qHeaderListStr = buildSignMemberStr(sortedSignHeaders);
    String qUrlParamListStr = buildSignMemberStr(sortedParams);
    String qKeyTimeStr, qSignTimeStr;
    qKeyTimeStr = qSignTimeStr = buildTimeStr(expiredTime);
    String signKey = HmacUtils.hmacSha1Hex(cred.getCOSSecretKey(), qKeyTimeStr);
    String formatMethod = methodName.toString().toLowerCase();
    String formatUri = resouce_path;
    String formatParameters = formatMapToStr(sortedParams);
    String formatHeaders = formatMapToStr(sortedSignHeaders);

    String formatStr = new StringBuilder().append(formatMethod).append(LINE_SEPARATOR)
            .append(formatUri).append(LINE_SEPARATOR).append(formatParameters)
            .append(LINE_SEPARATOR).append(formatHeaders).append(LINE_SEPARATOR).toString();
    String hashFormatStr = DigestUtils.sha1Hex(formatStr);
    String stringToSign = new StringBuilder().append(Q_SIGN_ALGORITHM_VALUE)
            .append(LINE_SEPARATOR).append(qSignTimeStr).append(LINE_SEPARATOR)
            .append(hashFormatStr).append(LINE_SEPARATOR).toString();
    String signature = HmacUtils.hmacSha1Hex(signKey, stringToSign);

    String authoriationStr = new StringBuilder().append(Q_SIGN_ALGORITHM_KEY).append("=")
            .append(Q_SIGN_ALGORITHM_VALUE).append("&").append(Q_AK).append("=")
            .append(cred.getCOSAccessKeyId()).append("&").append(Q_SIGN_TIME).append("=")
            .append(qSignTimeStr).append("&").append(Q_KEY_TIME).append("=").append(qKeyTimeStr)
            .append("&").append(Q_HEADER_LIST).append("=").append(qHeaderListStr).append("&")
            .append(Q_URL_PARAM_LIST).append("=").append(qUrlParamListStr).append("&")
            .append(Q_SIGNATURE).append("=").append(signature).toString();
    return authoriationStr;
}
 
Example 16
Project: ProjectAres   File: ListingServiceImpl.java   View Source Code Vote up 5 votes
@Override
public ListenableFuture<Reply> update(boolean online, CommandSender sender) {
    this.online = online;

    if(sessionId == null) {
        final byte[] bytes = new byte[20];
        random.nextBytes(bytes);
        sessionId = Hex.encodeHexString(bytes);
        sessionDigest = DigestUtils.sha1Hex(sessionId);
    }

    final ListenableFuture<Reply> future = http.post(config.announceUrl().toString(), new ListingUpdate() {
        @Override public @Nullable String host() {
            return config.serverHost();
        }

        @Override
        public int port() {
            return config.serverPort().orElseGet(localServer::getPort);
        }

        @Override
        public boolean online() {
            return online;
        }

        @Override
        public String session() {
            return sessionId;
        }
    }, Reply.class, HttpOption.INFINITE_RETRY);

    executor.callback(
        future,
        CommandFutureCallback.onSuccess(sender, reply -> {
            if(!online) {
                sessionId = sessionDigest = null;
            }

            audiences.get(sender).sendMessage(new TranslatableComponent(online ? "announce.online" : "announce.offline"));
        })
    );

    return future;
}
 
Example 17
Project: attendance-manager-back   File: SHA1Encoder.java   View Source Code Vote up 5 votes
@Override
public String encode(CharSequence rawPassword) {
	return DigestUtils.sha1Hex(rawPassword.toString());
}
 
Example 18
Project: Android_Code_Arbiter   File: WeakMessageDigest.java   View Source Code Vote up 5 votes
public static void apacheApiVariations() {

        printHex(DigestUtils.getMd2Digest().digest("123".getBytes()));
        printHex(DigestUtils.getMd5Digest().digest("123".getBytes()));
        printHex(DigestUtils.getDigest("md2").digest("123".getBytes()));
        printHex(DigestUtils.getDigest("md5").digest("123".getBytes()));
        DigestUtils.md2("123".getBytes());
        DigestUtils.md5("123".getBytes());
        System.out.println(DigestUtils.md2Hex("123".getBytes()));
        System.out.println(DigestUtils.md5Hex("123".getBytes()));

        printHex(DigestUtils.getSha1Digest().digest("123".getBytes()));
        printHex(DigestUtils.getShaDigest().digest("123".getBytes()));
        printHex(DigestUtils.getDigest("sha1").digest("123".getBytes()));
        printHex(DigestUtils.getDigest("sha-1").digest("123".getBytes()));
        DigestUtils.sha1("123".getBytes());
        DigestUtils.sha("123".getBytes());
        DigestUtils.sha1Hex("123".getBytes());
        DigestUtils.shaHex("123".getBytes());

        printHex(DigestUtils.getDigest("sha256").digest("123".getBytes())); //OK!
        printHex(DigestUtils.getDigest(getDigest()).digest("123".getBytes())); //Unknown
    }
 
Example 19
Project: Backmemed   File: ResourcePackRepository.java   View Source Code Vote up 5 votes
public ListenableFuture<Object> downloadResourcePack(String url, String hash)
{
    String s = DigestUtils.sha1Hex(url);
    final String s1 = SHA1.matcher(hash).matches() ? hash : "";
    final File file1 = new File(this.dirServerResourcepacks, s);
    this.lock.lock();

    try
    {
        this.clearResourcePack();

        if (file1.exists())
        {
            if (this.checkHash(s1, file1))
            {
                ListenableFuture listenablefuture2 = this.setResourcePackInstance(file1);
                ListenableFuture listenablefuture3 = listenablefuture2;
                return listenablefuture3;
            }

            LOGGER.warn("Deleting file {}", new Object[] {file1});
            FileUtils.deleteQuietly(file1);
        }

        this.deleteOldServerResourcesPacks();
        final GuiScreenWorking guiscreenworking = new GuiScreenWorking();
        Map<String, String> map = getDownloadHeaders();
        final Minecraft minecraft = Minecraft.getMinecraft();
        Futures.getUnchecked(minecraft.addScheduledTask(new Runnable()
        {
            public void run()
            {
                minecraft.displayGuiScreen(guiscreenworking);
            }
        }));
        final SettableFuture<Object> settablefuture = SettableFuture.<Object>create();
        this.downloadingPacks = HttpUtil.downloadResourcePack(file1, url, map, 52428800, guiscreenworking, minecraft.getProxy());
        Futures.addCallback(this.downloadingPacks, new FutureCallback<Object>()
        {
            public void onSuccess(@Nullable Object p_onSuccess_1_)
            {
                if (ResourcePackRepository.this.checkHash(s1, file1))
                {
                    ResourcePackRepository.this.setResourcePackInstance(file1);
                    settablefuture.set((Object)null);
                }
                else
                {
                    ResourcePackRepository.LOGGER.warn("Deleting file {}", new Object[] {file1});
                    FileUtils.deleteQuietly(file1);
                }
            }
            public void onFailure(Throwable p_onFailure_1_)
            {
                FileUtils.deleteQuietly(file1);
                settablefuture.setException(p_onFailure_1_);
            }
        });
        ListenableFuture listenablefuture = this.downloadingPacks;
        ListenableFuture listenablefuture11 = listenablefuture;
        return listenablefuture11;
    }
    finally
    {
        this.lock.unlock();
    }
}
 
Example 20
Project: CustomWorldGen   File: ResourcePackRepository.java   View Source Code Vote up 5 votes
public ListenableFuture<Object> downloadResourcePack(String url, String hash)
{
    String s = DigestUtils.sha1Hex(url);
    final String s1 = SHA1.matcher(hash).matches() ? hash : "";
    final File file1 = new File(this.dirServerResourcepacks, s);
    this.lock.lock();

    try
    {
        this.clearResourcePack();

        if (file1.exists())
        {
            if (this.checkHash(s1, file1))
            {
                ListenableFuture listenablefuture1 = this.setResourcePackInstance(file1);
                return listenablefuture1;
            }

            LOGGER.warn("Deleting file {}", new Object[] {file1});
            FileUtils.deleteQuietly(file1);
        }

        this.deleteOldServerResourcesPacks();
        final GuiScreenWorking guiscreenworking = new GuiScreenWorking();
        Map<String, String> map = getDownloadHeaders();
        final Minecraft minecraft = Minecraft.getMinecraft();
        Futures.getUnchecked(minecraft.addScheduledTask(new Runnable()
        {
            public void run()
            {
                minecraft.displayGuiScreen(guiscreenworking);
            }
        }));
        final SettableFuture<Object> settablefuture = SettableFuture.<Object>create();
        this.downloadingPacks = HttpUtil.downloadResourcePack(file1, url, map, 52428800, guiscreenworking, minecraft.getProxy());
        Futures.addCallback(this.downloadingPacks, new FutureCallback<Object>()
        {
            public void onSuccess(@Nullable Object p_onSuccess_1_)
            {
                if (ResourcePackRepository.this.checkHash(s1, file1))
                {
                    ResourcePackRepository.this.setResourcePackInstance(file1);
                    settablefuture.set((Object)null);
                }
                else
                {
                    ResourcePackRepository.LOGGER.warn("Deleting file {}", new Object[] {file1});
                    FileUtils.deleteQuietly(file1);
                }
            }
            public void onFailure(Throwable p_onFailure_1_)
            {
                FileUtils.deleteQuietly(file1);
                settablefuture.setException(p_onFailure_1_);
            }
        });
        ListenableFuture listenablefuture = this.downloadingPacks;
        return listenablefuture;
    }
    finally
    {
        this.lock.unlock();
    }
}