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

心已入冬 提交于 2019-12-02 18:13:39

问题


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
        }
    }

I'm doing the following in PHP, but the end result isn't matching:

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

What am I missing on the PHP side?


回答1:


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;

This way the base64_encoded raw value from PHP should be equal to the one that you get from base64EncodedString



来源:https://stackoverflow.com/questions/49929834/how-so-i-convert-this-sha256-base64-from-swift-to-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!