You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

86 lines
2.1 KiB

  1. package com.simple.utils;
  2. import java.security.MessageDigest;
  3. /**
  4. * @author Stormeye
  5. * @since 2018.08.09
  6. */
  7. public class HashUtil {
  8. private static final java.security.SecureRandom random = new java.security.SecureRandom();
  9. private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
  10. private static final char[] CHAR_ARRAY = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  11. .toCharArray();
  12. public static String md5(String srcStr) {
  13. return hash("MD5", srcStr);
  14. }
  15. public static String sha1(String srcStr) {
  16. return hash("SHA-1", srcStr);
  17. }
  18. public static String sha256(String srcStr) {
  19. return hash("SHA-256", srcStr);
  20. }
  21. public static String sha384(String srcStr) {
  22. return hash("SHA-384", srcStr);
  23. }
  24. public static String sha512(String srcStr) {
  25. return hash("SHA-512", srcStr);
  26. }
  27. public static String hash(String algorithm, String srcStr) {
  28. try {
  29. MessageDigest md = MessageDigest.getInstance(algorithm);
  30. byte[] bytes = md.digest(srcStr.getBytes("utf-8"));
  31. return toHex(bytes);
  32. } catch (Exception e) {
  33. throw new RuntimeException(e);
  34. }
  35. }
  36. private static String toHex(byte[] bytes) {
  37. StringBuilder ret = new StringBuilder(bytes.length * 2);
  38. for (int i = 0; i < bytes.length; i++) {
  39. ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
  40. ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
  41. }
  42. return ret.toString();
  43. }
  44. /**
  45. * md5 128bit 16bytes sha1 160bit 20bytes sha256 256bit 32bytes sha384
  46. * 384bit 48bytes sha512 512bit 64bytes
  47. */
  48. public static String generateSalt(int saltLength) {
  49. StringBuilder salt = new StringBuilder();
  50. for (int i = 0; i < saltLength; i++) {
  51. salt.append(CHAR_ARRAY[random.nextInt(CHAR_ARRAY.length)]);
  52. }
  53. return salt.toString();
  54. }
  55. public static String generateSaltForSha256() {
  56. return generateSalt(32);
  57. }
  58. public static String generateSaltForSha512() {
  59. return generateSalt(64);
  60. }
  61. public static boolean slowEquals(byte[] a, byte[] b) {
  62. if (a == null || b == null) {
  63. return false;
  64. }
  65. int diff = a.length ^ b.length;
  66. for (int i = 0; i < a.length && i < b.length; i++) {
  67. diff |= a[i] ^ b[i];
  68. }
  69. return diff == 0;
  70. }
  71. }