如何将SHA256 + BASE64从Swift转换为PHP? [英] How so I convert this SHA256 + BASE64 from Swift to PHP?
本文介绍了如何将SHA256 + BASE64从Swift转换为PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经获得了这个Swift代码来尝试在PHP中工作:
I've been given this Swift code to try and make work in PHP:
finalStr = Encryption.sha256(inputStr)
...
class Encryption {
static func sha256(_ data: Data) -> Data? {
guard let res = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH)) else { return nil }
CC_SHA256((data as NSData).bytes, CC_LONG(data.count), res.mutableBytes.assumingMemoryBound(to: UInt8.self))
return res as Data
}
static func sha256(_ str: String) -> String? {
guard
let data = str.data(using: String.Encoding.utf8),
let shaData = Encryption.sha256(data)
else { return nil }
let rc = shaData.base64EncodedString(options: [])
return rc
}
}
我正在PHP中执行以下操作,但最终结果不匹配:
I'm doing the following in PHP, but the end result isn't matching:
$hashedStr = hash('sha256', $inputStr);
$finalStr = base64_encode($hashedStr);
echo $finalStr;
我在PHP方面缺少什么?
What am I missing on the PHP side?
推荐答案
您应该将PHP中hash
方法的原始输出设置为true.请注意哈希
You should set raw output to true for hash
method in PHP. Notice the third method argument in hash
$hashedStr = hash('sha256', $inputStr, true);
$finalStr = base64_encode($hashedStr);
echo $finalStr;
这样,PHP的base64_encoded原始值应等于从base64EncodedString
This way the base64_encoded raw value from PHP should be equal to the one that you get from base64EncodedString
这篇关于如何将SHA256 + BASE64从Swift转换为PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文