hashPassword static method
This method takes a password and returns a hash calculated with the
bcrypt algorithm. The salt is added to enlarge the hash base
Implementation
static String hashPassword(String password, String salt) {
String realSalt;
var minor = 0;
int rounds;
var off = 0;
var rs = '';
if ((salt.codeUnitAt(0) != '\$'.codeUnitAt(0)) ||
(salt.codeUnitAt(1) != '2'.codeUnitAt(0))) {
throw Exception('Invalid salt version');
}
if (salt.codeUnitAt(2) == '\$'.codeUnitAt(0)) {
off = 3;
} else {
minor = salt.codeUnitAt(2);
if ((minor != 'a'.codeUnitAt(0)) ||
(salt.codeUnitAt(3) != '\$'.codeUnitAt(0))) {
throw Exception('Invalid salt revision');
}
off = 4;
}
if (salt.codeUnitAt(off + 2) > '\$'.codeUnitAt(0)) {
throw Exception('Missing salt rounds');
}
rounds = int.parse(salt.substring(off, off + 2));
realSalt = salt.substring(off + 3, off + 25);
var saltb = _decodeBase64(realSalt, bcryptSaltLen);
var hashed = BCrypt().encryptRaw(
Uint8List.fromList(
(password +
((minor >= 'a'.codeUnitAt(0)) ? String.fromCharCode(0) : ''))
.codeUnits,
),
saltb,
rounds,
Uint32List(bfCryptCiphertext.length)..setAll(0, bfCryptCiphertext),
);
rs += '\$2';
if (minor >= 'a'.codeUnitAt(0)) {
rs += String.fromCharCode(minor);
}
rs += '\$';
if (rounds < 10) {
rs += '0';
}
if (rounds > 30) {
throw Exception('rounds exceeds maximum (30)');
}
rs += rounds.toString();
rs += '\$';
rs += _encodeBase64(saltb, saltb.length);
rs += _encodeBase64(hashed, (bfCryptCiphertext.length * 4) - 1);
return rs;
}