如何从爪哇创建流星密码?

我正在尝试从Java代码生成有效的流星密码。


我知道流星使用bcrypt,它似乎在前面运行SHA-256哈希。但我无法让它发挥作用。有没有人成功地做到了这一点?我尝试过这样的事情:


String password = "secret123";

MessageDigest digest = MessageDigest.getInstance("SHA-256");

Charset scs = StandardCharsets.UTF_8;

//Charset scs = StandardCharsets.ISO_8859_1;

byte[] encodedhash = digest.digest(password.getBytes(scs));

String hash = new String(encodedhash, scs);

String bcrypt = BCrypt.hashpw(hash, BCrypt.gensalt());

这将返回一个看起来像有效bcrypt密码的字符串,但是流星在我将其存储在MongoDB中并尝试从流星代码登录后不接受它。


人到中年有点甜
浏览 110回答 1
1回答

江户川乱折腾

我想通了。SHA-256 的二进制结果必须格式化为十六进制数字字符串。这是工作代码:String password = "secret123";MessageDigest digest = MessageDigest.getInstance("SHA-256");Charset scs = StandardCharsets.UTF_8;byte[] encodedhash = digest.digest(password.getBytes(scs));String hash = toHexString(encodedhash);String bcrypt = BCrypt.hashpw(hash, BCrypt.gensalt());使用十六进制字符串,如下所示:&nbsp; &nbsp; private static char toHex(int nibble) {&nbsp; &nbsp; &nbsp; &nbsp; final char[] hexDigit = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};&nbsp; &nbsp; &nbsp; &nbsp; return hexDigit[nibble & 0xF];&nbsp; &nbsp; }&nbsp; &nbsp; public static String toHexString(byte[] bytes) {&nbsp; &nbsp; &nbsp; &nbsp; StringBuffer sb = new StringBuffer(bytes.length*2);&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < bytes.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(toHex(bytes[i] >> 4) );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(toHex(bytes[i]) );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return sb.toString();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java