JAVA 解码 SHA1 PRNG 生成的十六进制字节
JAVA Decode SHA1PRNG generated byte in hexa
我目前正在尝试实现密码哈希生成器。
但首先,我尝试像这样对随机生成的盐进行编码:
public static byte[] generateSalt()
throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8];
random.nextBytes(salt);
return salt;
}
我如何将其编码为十六进制,然后将其解码为原始状态?我只想向用户显示生成的 salt 的 hexa 值,这样他就可以在身份验证部分对其进行解码。当然这是为了学习目的。
我试过了:
try {
byte[] new_salt;
String salt_str;
new_salt = PasswordHash.generateSalt();
for(int i = 0; i < 8; i++) {
salt_str += new_salt[i];
}
out_new_salt.setText(salt_str);
}
catch (Exception e) {
System.out.print(e.getStackTrace() + "Something failed");
}
输出如下所示:67-55-352712114-12035
好吧,我可以得到每个字节的内容。
我尝试使用 Base 64 编码器,但它打印出未知字符,我认为这是因为字节数组的内容具有 2exp8 的值范围。
我尝试使用:
System.out.println(new String(new_salt));
但它也会打印未知值。使用 Charset.forName("ISO-8859-1") 和 Charset.forName("UTF-8") 但它不起作用。
UTF-8 打印未知字符,ISO-8859-1 奇怪地工作,但打印的数字没有字节数组的大小 ( 8 )
我认为 hexa 最适合我想做的事情。
我终于找到了我要找的东西。
这是我在这里找到的一个简单功能:
How to convert a byte array to a hex string in Java?
这对我来说非常有效。
这是函数:
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
看起来像这样:
我目前正在尝试实现密码哈希生成器。 但首先,我尝试像这样对随机生成的盐进行编码:
public static byte[] generateSalt()
throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8];
random.nextBytes(salt);
return salt;
}
我如何将其编码为十六进制,然后将其解码为原始状态?我只想向用户显示生成的 salt 的 hexa 值,这样他就可以在身份验证部分对其进行解码。当然这是为了学习目的。
我试过了:
try {
byte[] new_salt;
String salt_str;
new_salt = PasswordHash.generateSalt();
for(int i = 0; i < 8; i++) {
salt_str += new_salt[i];
}
out_new_salt.setText(salt_str);
}
catch (Exception e) {
System.out.print(e.getStackTrace() + "Something failed");
}
输出如下所示:67-55-352712114-12035 好吧,我可以得到每个字节的内容。 我尝试使用 Base 64 编码器,但它打印出未知字符,我认为这是因为字节数组的内容具有 2exp8 的值范围。 我尝试使用:
System.out.println(new String(new_salt));
但它也会打印未知值。使用 Charset.forName("ISO-8859-1") 和 Charset.forName("UTF-8") 但它不起作用。 UTF-8 打印未知字符,ISO-8859-1 奇怪地工作,但打印的数字没有字节数组的大小 ( 8 ) 我认为 hexa 最适合我想做的事情。
我终于找到了我要找的东西。 这是我在这里找到的一个简单功能:
How to convert a byte array to a hex string in Java? 这对我来说非常有效。
这是函数:
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
看起来像这样: