我试图用我的PHP代码解决这个问题。 原始代码构建在spring security 3.0框架中。并且我试图在php中获得相同的结果,因为我无法对Java代码进行更改。
public boolean matches(CharSequence rawPassword, String encodedPassword) {
byte[] digested = decode(encodedPassword);
byte[] salt = EncodingUtils.subArray(digested, 0, 8);
return matches(digested, digest(rawPassword, salt));
}
private byte[] decode(CharSequence encodedPassword) {
return Hex.decode(encodedPassword);
}
Hex.decode:
public static byte[] decode(CharSequence s) {
int nChars = s.length();
if (nChars % 2 != 0) {
throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
}
byte[] result = new byte[nChars / 2];
for (int i = 0; i < nChars; i += 2) {
int msb = Character.digit(s.charAt(i), 16);
int lsb = Character.digit(s.charAt(i + 1), 16);
if (msb < 0 || lsb < 0) {
throw new IllegalArgumentException("Non-hex character in input: " + s);
}
result[i / 2] = (byte)((msb << 4) | lsb);
}
return result;
}
EncodingUtils.subArray:
public static byte[] subArray(byte[] array, int beginIndex, int endIndex) {
int length = endIndex - beginIndex;
byte[] subarray = new byte[length];
System.arraycopy(array, beginIndex, subarray, 0, length);
return subarray;
}
private byte[] digest(CharSequence rawPassword, byte[] salt) {
byte[] digest = digester.digest(EncodingUtils.concatenate(salt, secret, Utf8.encode(rawPassword)));
return EncodingUtils.concatenate(salt, digest);
}
public byte[] digest(byte[] value) {
synchronized(messageDigest) {
for (int i = 0; i < iterations; i++) {
value = messageDigest.digest(value);
}
return value;
}
}
我的PHP代码使用
function alogs($password, $salt, $algo = 'SHA256', $count = 1024 ,$length = 80)
{
$password = strtolower($salt).strtolower($password);
for ($j = 1; $j < $count; $j++)
$password = hash($algo, $password);
return $password ? substr($password, 0, $length) : $password;
}
密码使用:'cwtcn' 和盐'12345678' 迭代1024
结果是java encodedPassword:
12345678e5246d4bb776fa6837cbecd5496a0c577c6b1d51a457e4ba68f600787deaad935640e1d2
在php中
123456781fdf4f326d05115f5ac31407302aa8cd614f11950e15bd6723b0266bb23812b9