publicstatic String byteArrayToHexString(byte b[]){ StringBuffer resultSb = new StringBuffer(); for(int i = 0; i < b.length; i++){ resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); }
publicstatic String byteToHexString(byte b){ int n = b; if(n < 0){ n += 256; } int d1 = n / 16; int d2 = n % 16; return hexDigIts[d1] + hexDigIts[d2]; }
publicclassBcryptCipher{ // generate salt seed privatestaticfinalint SALT_SEED = 12; // the head fo salt privatestaticfinal String SALT_STARTSWITH = "$2a$12";
publicstaticfinal String SALT_KEY = "salt";
publicstaticfinal String CIPHER_KEY = "cipher";
/** * Bcrypt encryption algorithm method * @param encryptSource * need to encrypt the string * @return Map , two values in Map , salt and cipher */ publicstatic Map<String, String> Bcrypt(final String encryptSource){ String salt = BCrypt.gensalt(SALT_SEED); Map<String, String> bcryptResult = Bcrypt(salt, encryptSource); return bcryptResult; } /** * * @param salt encrypt salt, Must conform to the rules * @param encryptSource * @return */ publicstatic Map<String, String> Bcrypt(final String salt, final String encryptSource){ if (StringUtils.isBlank(encryptSource)) { thrownew RuntimeException("Bcrypt encrypt input params can not be empty"); }
if (StringUtils.isBlank(salt) || salt.length() != 29) { thrownew RuntimeException("Salt can't be empty and length must be to 29"); } if (!salt.startsWith(SALT_STARTSWITH)) { thrownew RuntimeException("Invalid salt version, salt version is $2a$12"); }