我的wordpress后端正在使用phpass哈希算法并使用网络服务给我phpass。在swos的ios结尾,我试图在swift中生成相同的phpass哈希。下面是swift和php中的代码。两者都有相同的输入但输出不同。所以问题是我怎样才能获得相同的输出。我错过了什么吗?
Php代码:
If Not DeleteUsername(TheFile,TheUsername) then
ShowMessage('User was not found, what were you thinking!');
Swift代码:
<?php
function phpassHash($password, $salt,$iterations){
$hash = hash('md5', $salt.$password, TRUE);
for($i = 0; $i < $iterations; $i++){
$hash = hash('md5', $hash.$password, TRUE);
}
return $hash;
}
$result = phpassHash("a_test_password","MsdvACyA", 8192);
echo bin2hex($result);
?>
答案 0 :(得分:1)
您太急于将字节数组转换为String
函数中的md5
。例如,这会将整数0x47
的含义更改为字符串47
。您对md5()
的第一次调用会返回正确的哈希值,但如果再次md5()
,则会出错,因为它现在是字符串而不是PHP中的字节数组。请注意,在PHP中,您在最后一步调用bin2hex
。
由于CommonCrypt中的CC_MD5
函数喜欢处理字节数组,因此必要时将所有内容保存为字节和编写器包装。
首先,让我们定义一些辅助函数:
extension String {
// Return the bytes that make up the string according to UTF-8 encoding
var bytes: [UInt8] {
get {
return self.cStringUsingEncoding(NSUTF8StringEncoding)!
.dropLast() // C strings are null-terminated so we need to drop the last byte
.map { UInt8(bitPattern: $0) }
}
}
}
// Convert an array of bytes to a hex string
func toHexString(bytes: [UInt8]) -> String {
return bytes.map { String(format: "%02x", $0) }.joinWithSeparator("")
}
现在你可以写你的哈希函数了:
// Allow you to quickly hash a string. We don't really use it here
func md5(string: String) -> [UInt8] {
return md5(string.bytes)
}
func md5(bytes: [UInt8]) -> [UInt8] {
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
CC_MD5(bytes, CC_LONG(bytes.count), &digest)
return digest
}
func phpassHash(password: String, salt: String, iterations: Int) -> [UInt8] {
let passwordBytes = password.bytes
let saltBytes = salt.bytes
var hash = md5(saltBytes + passwordBytes)
for _ in 0..<iterations {
hash = md5(hash + passwordBytes)
}
return hash
}
let password = "a_test_password"
let salt = "MsdvACyA"
let iterations = 8192
let assHash = phpassHash(password, salt: salt, iterations: iterations)
print(toHexString(assHash)) // 42a89278a28860f223a10fdb43b5d4b2