简体   繁体   English

我如何将这个 SHA256 + BASE64 从 Swift 转换为 PHP?

[英]How so I convert this SHA256 + BASE64 from Swift to PHP?

I've been given this Swift code to try and make work in PHP:我得到了这个 Swift 代码来尝试在 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
        }
    }

I'm doing the following in PHP, but the end result isn't matching:我在 PHP 中执行以下操作,但最终结果不匹配:

$hashedStr = hash('sha256', $inputStr);
$finalStr = base64_encode($hashedStr);
echo $finalStr;

What am I missing on the PHP side?我在 PHP 方面缺少什么?

You should set raw output to true for hash method in PHP.对于 PHP 中的hash方法,您应该将原始输出设置为 true。 Notice the third method argument in hash注意哈希中的第三个方法参数

$hashedStr = hash('sha256', $inputStr, true);
$finalStr = base64_encode($hashedStr);
echo $finalStr;

This way the base64_encoded raw value from PHP should be equal to the one that you get from base64EncodedString这样,来自 PHP 的 base64_encoded 原始值应该等于您从base64EncodedString获得的base64EncodedString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM