【问题标题】:Convert hashed byte array into String将散列字节数组转换为字符串
【发布时间】:2013-04-21 04:05:26
【问题描述】:

如果我这样做

int keyLength = 160; // because SHA1 generates 160-bit hashes
int iterations = 20 * 1000; //standard is 2000 but let's be more secure here

KeySpec spec = new PBEKeySpec(password.toCharArray(), generateSalt(), iterations, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = keyFactory.generateSecret(spec).getEncoded();

如何将此哈希转换为字符串以便可以将其保存到 DB 中?我尝试了 new String(hash, "UTF-8");,但它给出了格式错误的字符,例如 l��0\�w�c��Q�

【问题讨论】:

    标签: java string hash bytearray


    【解决方案1】:

    您需要将字节数组编码为Base64 string,然后在从数据库中读取它时将其解码回字节数组。请注意,编码后的字符串将比原始字节数组大 33% 左右。

    【讨论】:

      【解决方案2】:

      如果您始终在应用程序中将密钥作为byte[] 使用,那么将其作为 BLOB 二进制对象本身保存在数据库中会好得多。您可以避免转换错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多