Search code examples
phpswiftbase64sha

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:

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?


Solution

  • 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