工具类

  1. public class BcryptCipher {
  2. // generate salt seed
  3. private static final int SALT_SEED = 12;
  4. // the head fo salt
  5. private static final String SALT_STARTSWITH = "$2a$12";
  6. public static final String SALT_KEY = "salt";
  7. public static final String CIPHER_KEY = "cipher";
  8. /**
  9. * Bcrypt encryption algorithm method
  10. * @param encryptSource
  11. * need to encrypt the string
  12. * @return Map , two values in Map , salt and cipher
  13. */
  14. public static Map<String, String> Bcrypt(final String encryptSource) {
  15. String salt = BCrypt.gensalt(SALT_SEED);
  16. Map<String, String> bcryptResult = Bcrypt(salt, encryptSource);
  17. return bcryptResult;
  18. }
  19. /**
  20. *
  21. * @param salt encrypt salt, Must conform to the rules
  22. * @param encryptSource
  23. * @return
  24. */
  25. public static Map<String, String> Bcrypt(final String salt, final String encryptSource) {
  26. if (StringUtils.isBlank(encryptSource)) {
  27. throw new RuntimeException("Bcrypt encrypt input params can not be empty");
  28. }
  29. if (StringUtils.isBlank(salt) || salt.length() != 29) {
  30. throw new RuntimeException("Salt can't be empty and length must be to 29");
  31. }
  32. if (!salt.startsWith(SALT_STARTSWITH)) {
  33. throw new RuntimeException("Invalid salt version, salt version is $2a$12");
  34. }
  35. String cipher = BCrypt.hashpw(encryptSource, salt);
  36. Map<String, String> bcryptResult = new HashMap<String, String>();
  37. bcryptResult.put(SALT_KEY, salt);
  38. bcryptResult.put(CIPHER_KEY, cipher);
  39. return bcryptResult;
  40. }
  41. }

测试


/**
 * BCrypt加密
 */
public class BCryptTest {

  public static void main(String[] args) {

    String string = "我是一句话";
    Map<String, String> bcrypt = BcryptCipher.Bcrypt(string);
    System.out.println(bcrypt.keySet()); //[cipher, salt]

    System.out.println(bcrypt.get("cipher")); //$2a$12$ylb92Z84gqlrSfzIztlCV.dK0xNbw.pOv3UwXXA76llOsNRTJsE/.
    System.out.println(bcrypt.get("salt")); //$2a$12$ylb92Z84gqlrSfzIztlCV.

    Map<String, String> bcrypt2 = BcryptCipher.Bcrypt(bcrypt.get("salt"),string);
    System.out.println(bcrypt2.get("SALT_KEY")); //null
    System.out.println(bcrypt2.get("CIPHER_KEY")); //null
  }
}