JAVA解码SHA1PRNG生成的十六进制字节
我目前正在尝试实现一个密码哈希生成器。 但首先,我尝试对随机生成的盐进行如下编码:JAVA解码SHA1PRNG生成的十六进制字节,java,encoding,character-encoding,hex,secure-random,Java,Encoding,Character Encoding,Hex,Secure Random,我目前正在尝试实现一个密码哈希生成器。 但首先,我尝试对随机生成的盐进行如下编码: public static byte[] generateSalt() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[8]; random.nextBytes(salt); ret
public static byte[] generateSalt()
throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8];
random.nextBytes(salt);
return salt;
}
我如何将其编码为六进制,然后将其解码为原始状态?我只想向用户显示生成的salt的hexa值,这样用户就可以在authenticate部分对其进行解码。当然这是为了学习
我试过这个:
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");
}
但它也打印出未知的值。使用Charset.forName(“ISO-8859-1”)和Charset.forName(“UTF-8”)但不起作用。
UTF-8打印未知字符,ISO-8859-1的工作原理很奇怪,但打印的数字不如字节数组(8)的大小
我认为hexa最适合我想做的事情 我终于找到了我想要的东西。 这是我在这里找到的一个简单的功能: 这对我来说非常有效 这就是功能:
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);
}
private final static char[]hexArray=“0123456789ABCDEF.tocharray();
公共静态字符串bytesToHex(字节[]字节){
char[]hexChars=新字符[bytes.length*2];
对于(int j=0;j>>4];
hexChars[j*2+1]=hexArray[v&0x0F];
}
返回新字符串(hexChars);
}
这看起来像这样:
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);
}