java加密MD5,SHA-1,SHA-256,默认使用SHA-256

电玩女神 2024-04-17 05:40 147阅读 0赞

加密,对应php的代码 hash(‘sha256’, ‘xxx’);

方式一、

  1. /**
  2. * 对字符串加密,加密算法使用MD5,SHA-1,SHA-256,默认使用SHA-256
  3. * @param strSrc 要加密的字符串
  4. * @param encName 加密类型
  5. * @return
  6. */
  7. public static String encrypt(String strSrc, String encName) {
  8. MessageDigest md = null;
  9. String strDes = null;
  10. byte[] bt = strSrc.getBytes();
  11. try {
  12. if (BeanUtil.isEmpty(encName)) {
  13. encName = "SHA-256";
  14. }
  15. md = MessageDigest.getInstance(encName);
  16. md.update(bt);
  17. strDes = bytes2Hex(md.digest()); // to HexString
  18. } catch (NoSuchAlgorithmException e) {
  19. return null;
  20. }
  21. return strDes;
  22. }
  23. public static String bytes2Hex(byte[] bts) {
  24. String des = "";
  25. String tmp = null;
  26. for (int i = 0; i < bts.length; i++) {
  27. tmp = (Integer.toHexString(bts[i] & 0xFF));
  28. if (tmp.length() == 1) {
  29. des += "0";
  30. }
  31. des += tmp;
  32. }
  33. return des;
  34. }

方式二、

以下传入的字符串是方式一种strSrc拼接之前的参数,实际两种方式的参数比较后相当于

  1. String strSrc = channelID + channelKey + appID + userID + nonce + timestamp;
  2. public static String createToken(String channelId, String channelKey, String appId, String userId,String nonce, Integer timestamp) throws NoSuchAlgorithmException {
  3. MessageDigest digest = MessageDigest.getInstance("SHA-256");
  4. digest.update(channelId.getBytes());
  5. digest.update(channelKey.getBytes());
  6. digest.update(appId.getBytes());
  7. digest.update(userId.getBytes());
  8. digest.update(nonce.getBytes());
  9. digest.update(Long.toString(timestamp).getBytes());
  10. String token = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
  11. return token;
  12. }

发表评论

表情:
评论列表 (有 0 条评论,147人围观)

还没有评论,来说两句吧...

相关阅读