gpt4 book ai didi

java - org.apache.commons.codec.digest.Crypt 导致无效盐值异常

转载 作者:行者123 更新时间:2023-12-04 08:00:39 27 4
gpt4 key购买 nike

以下代码导致 java.lang.IllegalArgumentException随机但不总是在一台计算机上,而不是用于测试的其他计算机。异常原因是Invalid salt value: $6$+E3Vebci/+lhkquntg== .使用 SHA512 ( $6$ ) 调用 Crypt.crypt() 时。我可以看到 Crypt 有一个模式来检查有效的盐:“^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*“ .
JDK 是 openjdk 15.0.1 2020-10-20,commons-codec 是 1.15 版本。
我只是想知道为什么这会随机发生在一台 Windows 10 计算机上,而不是在另一台计算机上(M1 上的 macOS Big Sur)。然后我是否应该以不同的方式创建盐以避免出现此异常?从网上搜索时没有找到类似的东西。

byte bytes[] = new byte[13]; 
secureRandom.nextBytes(bytes); // java.security.SecureRandom
String saltBytes = new String(Base64.getEncoder().encode(bytes));
String salt = "$6$" + saltBytes;
String hashedPassword = Crypt.crypt(user.getPassword(), salt);
堆栈跟踪结束于 org.apache.commons.codec.digest.Sha2Crypt.sha2Crypt在第 181 行。
PC 是 MateBook D Intel Core i7-855OU,Windows 10 Home v 1909 build 18363.1379

最佳答案

来自 crypto(String key, String salt) 的文档

The exact algorithm depends on the format of the salt string:

  • SHA-512 salts start with $6$ and are up to 16 chars long.
    ...
    The rest of the salt string is drawn from the set [a-zA-Z0-9./] and is cut at the maximum length of if a "$" sign is encountered.
    ...
    Throws:
    IllegalArgumentException - if the salt does not match the allowed pattern

由于 Base64 编码的字符串可能包含“=”、“+”,这在正则表达式中是不允许的 [a-zA-Z0-9./] , 当生成的 salt 中出现一些无效字符时,您会随机看到错误.
解决方案:
  • 只需使用 crypto(String key) 相反,因为它已经提供了随机盐。
  • 或者按照允许的模式生成盐。

  • 引用:
    rfc4648 - Table 1: The Base 64 Alphabet

    关于java - org.apache.commons.codec.digest.Crypt 导致无效盐值异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66493605/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com