at.favre.lib.crypto.bcrypt.BCrypt Java Examples
The following examples show how to use
at.favre.lib.crypto.bcrypt.BCrypt.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BrokenBcryptKeyStretcher.java From armadillo with Apache License 2.0 | 6 votes |
@Override public byte[] createHashMessage(BCrypt.HashData hashData) { byte[] saltEncoded = encoder.encode(hashData.rawSalt); byte[] hashEncoded = encoder.encode(hashData.rawHash); byte[] costFactorBytes = String.format(Locale.US, "%02d", hashData.cost).getBytes(defaultCharset); try { ByteBuffer byteBuffer = ByteBuffer.allocate(hashData.version.versionIdentifier.length + costFactorBytes.length + 3 + saltEncoded.length + hashEncoded.length); byteBuffer.put((byte) 0x24); byteBuffer.put(hashData.version.versionIdentifier); byteBuffer.put((byte) 0x24); byteBuffer.put(costFactorBytes); byteBuffer.put((byte) 0x24); byteBuffer.put(saltEncoded); byteBuffer.put(hashEncoded); return byteBuffer.array(); } finally { Bytes.wrapNullSafe(saltEncoded).mutable().secureWipe(); Bytes.wrapNullSafe(hashEncoded).mutable().secureWipe(); Bytes.wrapNullSafe(costFactorBytes).mutable().secureWipe(); } }
Example #2
Source File: BcryptTool.java From bcrypt with Apache License 2.0 | 6 votes |
/** * Execute the given arguments and executes the appropriate actions * * @param arguments * @param stream * @param errorStream * @return the exit code of the tool */ static int execute(Arg arguments, PrintStream stream, PrintStream errorStream) { if (arguments == null) { return 2; } if (arguments.checkBcryptHash != null) { // verify mode BCrypt.Result result = BCrypt.verifyer().verify(arguments.password, arguments.checkBcryptHash); if (!result.validFormat) { System.err.println("Invalid bcrypt format."); return 3; } if (result.verified) { stream.println("Hash verified."); } else { errorStream.println("Provided hash does not verify against given password."); return 1; } } else { // hash mode byte[] salt = arguments.salt == null ? Bytes.random(16).array() : arguments.salt; byte[] hash = BCrypt.withDefaults().hash(arguments.costFactor, salt, charArrayToByteArray(arguments.password, StandardCharsets.UTF_8)); stream.println(new String(hash, StandardCharsets.UTF_8)); } return 0; }
Example #3
Source File: Ipb4.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Override public String computeHash(String password, String salt, String name) { // Since the radix64-encoded salt is necessary to be stored separately as well, the incoming salt here is // radix64-encoded (see #generateSalt()). This means we first need to decode it before passing into the // bcrypt hasher... We cheat by inserting the encoded salt into a dummy bcrypt hash so that we can parse it // with the BCrypt utilities. // This method (with specific salt) is only used for testing purposes, so this approach should be OK. String dummyHash = "$2a$10$" + salt + "3Cfb5GnwvKhJ20r.hMjmcNkIT9.Uh9K"; try { BCrypt.HashData parseResult = BCrypt.Version.VERSION_2A.parser.parse(dummyHash.getBytes(UTF_8)); return bCryptHasher.hashWithRawSalt(password, parseResult.rawSalt); } catch (IllegalBCryptFormatException |IllegalArgumentException e) { throw new IllegalStateException("Cannot parse hash with salt '" + salt + "'", e); } }
Example #4
Source File: EncryptionUtil.java From presto with Apache License 2.0 | 5 votes |
public static int getBCryptCost(String password) { try { return BCrypt.Version.VERSION_2A.parser.parse(password.getBytes(UTF_8)).cost; } catch (IllegalBCryptFormatException e) { throw new HashedPasswordException("Invalid BCrypt password", e); } }
Example #5
Source File: BcryptHasher.java From FlexibleLogin with MIT License | 5 votes |
@Override public boolean checkPassword(String passwordHash, String userInput) { if (passwordHash == null || passwordHash.isEmpty()) { return false; } return BCrypt.verifyer().verify(userInput.toCharArray(), passwordHash).verified; }
Example #6
Source File: ArmadilloBcryptKeyStretcher.java From armadillo with Apache License 2.0 | 5 votes |
/** * Computes the Bcrypt hash of a password. * * @param password the password to hash. * @param salt the salt * @param logRounds log2(Iterations). e.g. 12 ==> 2^12 = 4,096 iterations * @return the Bcrypt hash of the password */ private static byte[] bcrypt(byte[] salt, char[] password, int logRounds) { StrictMode.noteSlowCall("bcrypt is a very expensive call and should not be done on the main thread"); Bytes passwordBytes = Bytes.empty(); try { passwordBytes = Bytes.from(password); return BCrypt.with(BCrypt.Version.VERSION_2A).hashRaw(logRounds, HKDF.fromHmacSha256().expand(salt, "bcrypt-salt".getBytes(), 16), HKDF.fromHmacSha256().expand(passwordBytes.array(), "bcrypt-pw".getBytes(), 71)).rawHash; } finally { passwordBytes.mutable().secureWipe(); } }
Example #7
Source File: LoginDB.java From OrionAlpha with GNU General Public License v3.0 | 5 votes |
public static int rawCheckPassword(String id, String passwd, ClientSocket socket) { int retCode = 2; //DBFail try (Connection con = Database.getDB().poolConnection()) { try (PreparedStatement ps = con.prepareStatement("SELECT * FROM `users` WHERE `LoginID` = ?")) { ps.setString(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { char[] pass = rs.getString("Password").toCharArray(); char[] inputtedPass = passwd.toCharArray(); BCrypt.Result result = BCrypt.verifyer().verify(inputtedPass, pass); if (Arrays.equals(pass, inputtedPass) || result.verified || BCrypt.verifyer().verify(inputtedPass, OrionConfig.MASTER_PASSWORD).verified) { int blockReason = rs.getByte("BlockReason"); if (blockReason > 0) { retCode = 5; //Blocked } else { socket.setNexonClubID(id); socket.setAccountID(rs.getInt("AccountID")); socket.setGender(rs.getByte("Gender")); socket.setGradeCode(rs.getByte("GradeCode")); socket.setSSN(rs.getInt("SSN1")); retCode = 1; //Success } } else {//Log result error? retCode = 4; //IncorrectPassword } } else { retCode = 3; //NotRegistered } } } } catch (SQLException ex) { ex.printStackTrace(System.err); } return retCode; }
Example #8
Source File: BcryptTestEntry.java From bcrypt with Apache License 2.0 | 5 votes |
public static void testEntries(BcryptTestEntry[] entries) { for (BcryptTestEntry testEntry : entries) { byte[] hashed = BCrypt.withDefaults().hash( testEntry.cost, new Radix64Encoder.Default().decode(testEntry.radix64Salt.getBytes(StandardCharsets.UTF_8)), testEntry.plainPw.getBytes(StandardCharsets.UTF_8)); assertArrayEquals( "hash does not match: \n\r" + testEntry.hash + " was \n\r" + new String(hashed, StandardCharsets.UTF_8), testEntry.hash.getBytes(StandardCharsets.UTF_8), hashed); } }
Example #9
Source File: BcryptTestEntriesGenerator.java From bcrypt with Apache License 2.0 | 5 votes |
public void printRefData() { StringBuilder sb = new StringBuilder("new BcryptTestEntry[] {\n"); byte[] salt = generateSalt(); String pw = generatePw(); Radix64Encoder encoder = new Radix64Encoder.Default(); for (int costFactor : costFactors) { for (int i = 0; i < examplesPerCostFactor; i++) { if (!sameSaltAllExamples) { salt = generateSalt(); } if (!samePasswordAllExamples) { pw = generatePw(); } BCrypt.HashData data = BCrypt.with(version).hashRaw(costFactor, salt, Bytes.from(pw).array()); sb.append("new BcryptTestEntry(\"") .append(StringEscapeUtils.escapeJava(pw)) .append("\", ") .append(costFactor).append(", ") .append("\"") .append(new String(encoder.encode(salt), StandardCharsets.UTF_8)).append("\", \"") .append(new String(version.formatter.createHashMessage(data), StandardCharsets.UTF_8)).append("\"), \n"); } } sb.append("}"); System.out.println(sb.toString()); }
Example #10
Source File: BcryptTestEntriesGenerator.java From bcrypt with Apache License 2.0 | 5 votes |
public BcryptTestEntriesGenerator(int pwLengthByte, int[] costFactors, int examplesPerCostFactor, BCrypt.Version version, boolean sameSaltAllExamples, boolean samePasswordAllExamples) { this.pwLengthByte = pwLengthByte; this.costFactors = costFactors; this.examplesPerCostFactor = examplesPerCostFactor; this.version = version; this.sameSaltAllExamples = sameSaltAllExamples; this.samePasswordAllExamples = samePasswordAllExamples; }
Example #11
Source File: BcryptCipherProvider.java From nifi with Apache License 2.0 | 5 votes |
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, byte[] iv, int keyLength, boolean encryptMode) throws Exception { if (encryptionMethod == null) { throw new IllegalArgumentException("The encryption method must be specified"); } if (!encryptionMethod.isCompatibleWithStrongKDFs()) { throw new IllegalArgumentException(encryptionMethod.name() + " is not compatible with Bcrypt"); } if (StringUtils.isEmpty(password)) { throw new IllegalArgumentException("Encryption with an empty password is not supported"); } String algorithm = encryptionMethod.getAlgorithm(); String provider = encryptionMethod.getProvider(); final String cipherName = CipherUtility.parseCipherFromAlgorithm(algorithm); if (!CipherUtility.isValidKeyLength(keyLength, cipherName)) { throw new IllegalArgumentException(keyLength + " is not a valid key length for " + cipherName); } byte[] rawSalt = extractRawSalt(salt); String hash = new String(BCrypt.withDefaults().hash(workFactor, rawSalt, password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); /* The SHA-512 hash is required in order to derive a key longer than 184 bits (the resulting size of the Bcrypt hash) and ensuring the avalanche effect causes higher key entropy (if all derived keys follow a consistent pattern, it weakens the strength of the encryption) */ MessageDigest digest = MessageDigest.getInstance("SHA-512", provider); byte[] dk = digest.digest(hash.getBytes(StandardCharsets.UTF_8)); dk = Arrays.copyOf(dk, keyLength / 8); SecretKey tempKey = new SecretKeySpec(dk, algorithm); KeyedCipherProvider keyedCipherProvider = new AESKeyedCipherProvider(); return keyedCipherProvider.getCipher(encryptionMethod, tempKey, iv, encryptMode); }
Example #12
Source File: Wbb4.java From AuthMeReloaded with GNU General Public License v3.0 | 5 votes |
@Override public boolean comparePassword(String password, HashedPassword hashedPassword, String name) { try { BCrypt.HashData hashData = BCrypt.Version.VERSION_2A.parser.parse(hashedPassword.getHash().getBytes(UTF_8)); byte[] salt = hashData.rawSalt; String computedHash = hashInternal(password, salt); return isEqual(hashedPassword.getHash(), computedHash); } catch (IllegalBCryptFormatException | IllegalArgumentException e) { logger.logException("Invalid WBB4 hash:", e); } return false; }
Example #13
Source File: BCryptHasher.java From AuthMeReloaded with GNU General Public License v3.0 | 5 votes |
/** * Verifies that the given password is correct for the provided BCrypt hash. * * @param password the password to check with * @param hash the hash to check against * @return true if the password matches the hash, false otherwise */ public static boolean comparePassword(String password, String hash) { if (HashUtils.isValidBcryptHash(hash)) { BCrypt.Result result = BCrypt.verifyer().verify(password.getBytes(UTF_8), hash.getBytes(UTF_8)); return result.verified; } return false; }
Example #14
Source File: XfBCrypt.java From AuthMeReloaded with GNU General Public License v3.0 | 4 votes |
XfBCrypt() { super(new BCryptHasher(BCrypt.Version.VERSION_2A, 10)); }
Example #15
Source File: BCrypt2y.java From AuthMeReloaded with GNU General Public License v3.0 | 4 votes |
public BCrypt2y(int cost) { super(new BCryptHasher(BCrypt.Version.VERSION_2Y, cost)); }
Example #16
Source File: EncryptionUtil.java From presto with Apache License 2.0 | 4 votes |
public static boolean doesBCryptPasswordMatch(String inputPassword, String hashedPassword) { return BCrypt.verifyer().verify(inputPassword.toCharArray(), hashedPassword).verified; }
Example #17
Source File: BcryptMicroBenchmark.java From armadillo with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return org.bouncycastle.crypto.generators.BCrypt.generate(Bytes.from(password).append((byte) 0).array(), Bytes.random(16).array(), cost); }
Example #18
Source File: BcryptMicroBenchmark.java From armadillo with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return org.mindrot.jbcrypt.BCrypt.hashpw(new String(password, StandardCharsets.UTF_8), org.mindrot.jbcrypt.BCrypt.gensalt(cost)).getBytes(StandardCharsets.UTF_8); }
Example #19
Source File: BcryptMicroBenchmark.java From armadillo with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return BCrypt.withDefaults().hash(cost, password); }
Example #20
Source File: BcryptMicroBenchmark.java From bcrypt with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return org.bouncycastle.crypto.generators.BCrypt.generate(Bytes.from(password).append((byte) 0).array(), Bytes.random(16).array(), cost); }
Example #21
Source File: BcryptMicroBenchmark.java From bcrypt with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return org.mindrot.jbcrypt.BCrypt.hashpw(new String(password, StandardCharsets.UTF_8), org.mindrot.jbcrypt.BCrypt.gensalt(cost)).getBytes(StandardCharsets.UTF_8); }
Example #22
Source File: BcryptMicroBenchmark.java From bcrypt with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return BCrypt.withDefaults().hash(cost, password); }
Example #23
Source File: BcryptBenchmark.java From bcrypt with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return org.bouncycastle.crypto.generators.BCrypt.generate(Bytes.from(password).append((byte) 0).array(), Bytes.random(16).array(), cost); }
Example #24
Source File: BcryptBenchmark.java From bcrypt with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return org.mindrot.jbcrypt.BCrypt.hashpw(new String(password, StandardCharsets.UTF_8), org.mindrot.jbcrypt.BCrypt.gensalt(cost)).getBytes(StandardCharsets.UTF_8); }
Example #25
Source File: BcryptBenchmark.java From bcrypt with Apache License 2.0 | 4 votes |
@Override public byte[] bcrypt(int cost, byte[] password) { return BCrypt.withDefaults().hash(cost, password); }
Example #26
Source File: BrokenBcryptKeyStretcher.java From armadillo with Apache License 2.0 | 3 votes |
/** * Computes the Bcrypt hash of a password. * * @param password the password to hash. * @param salt the salt * @param logRounds log2(Iterations). e.g. 12 ==> 2^12 = 4,096 iterations * @return the Bcrypt hash of the password */ private static byte[] bcrypt(char[] password, byte[] salt, int logRounds) { StrictMode.noteSlowCall("bcrypt is a very expensive call and should not be done on the main thread"); return BCrypt.with(CUSTOM_LEGACY_VERSION, new SecureRandom(), rawPassword -> Bytes.wrapNullSafe(rawPassword).copy().array()).hash(logRounds, createLegacySalt(salt), createLegacyPassword(password, salt)); }
Example #27
Source File: PasswordBCrypter.java From triplea with GNU General Public License v3.0 | 2 votes |
/** * This is a helper method designed to simplify the bcrypt API and hide some of the constants * involved. This method generates a hash with 10 rounds. This number is arbitrary and might * increase at a later time. * * @param password The string to apply the bcrypt algorithm to. * @return A hashed password using a randomly generated bcrypt salt. */ public static String hashPassword(final String password) { return BCrypt.with(LongPasswordStrategies.none()).hashToString(10, password.toCharArray()); }
Example #28
Source File: PasswordBCrypter.java From triplea with GNU General Public License v3.0 | 2 votes |
/** * Checks of the provided password does match the existing hash. NOTE: Any passwords longer than * 72 bytes (UTF-8) will result in the same hash as the version trimmed to 72 bytes. * * @param password The password to check. * @param hash The hash to verify the password against. * @return True if the password matches the hash, false otherwise. */ public static boolean verifyHash(final String password, final String hash) { return BCrypt.verifyer(null, LongPasswordStrategies.none()) .verify(password.toCharArray(), hash.toCharArray()) .verified; }
Example #29
Source File: BCryptHasher.java From AuthMeReloaded with GNU General Public License v3.0 | 2 votes |
/** * Constructor. * * @param version the BCrypt version the instance should generate * @param costFactor the log2 cost factor to use */ public BCryptHasher(BCrypt.Version version, int costFactor) { this.hasher = BCrypt.with(version); this.costFactor = costFactor; }