SecureRandom生成不同长度的值

Bri*_*nis 1 java salt

我有一个应用程序,我需要盐密码.为了产生我决定使用的盐SecureRandom.当我在我的Windows机器上时,一切都很好.然后我尝试在基于Linux的机器(Centos 5)上运行我的代码,一切都破了.

我隔离了问题并创建了这个测试用例:

public static void main(String[] args)  {
    SecureRandom sr = new SecureRandom();
    byte[] saltBytes = new byte[256];
    sr.nextBytes(saltBytes);
    String salt = new String(saltBytes);
    System.out.println(salt.length());
}
Run Code Online (Sandbox Code Playgroud)

在Windows中,输出总是256,但在我的Linux机器上,输出发生变化,从不变为256.它似乎总是生成一个长度小于256的盐.

有谁知道为什么会这样?

解:

我刚刚将新的String line更改为 new String(saltbytes, "ASCII");

kih*_*eru 5

问题是字符编码.在linux上通常是utf-8,这是一个可变长度编码.如果你想要一个字符串,请使用base64代替它.