如何将Swift中的SHA256+BASE64逻辑转换为PHP实现?
Converting Swift SHA256 Implementation to PHP
Got it, let's translate your Swift SHA256 logic into PHP. Here's a breakdown of how to replicate both of your Encryption class methods, plus the exact usage you're using for finalStr = Encryption.sha256(inputStr):
What Your Swift Code Does
- The
sha256(_ str: String)method takes a string, converts it to UTF-8 data, computes the SHA256 hash (raw bytes), then converts those bytes to a hexadecimal string (the missing part of your code snippet is almost certainly converting the resulting Data to a hex string). - The
sha256(_ data: Data)method computes the raw SHA256 digest directly from binary data.
PHP Equivalent for String-to-Hex SHA256
This matches the sha256(_ str: String) method you're using, including handling cases where the string can't be encoded as UTF-8 (returning null just like Swift does):
function sha256(string $str): ?string { // Validate UTF-8 encoding to mirror Swift's nil return on failure if (!mb_check_encoding($str, 'UTF-8')) { return null; } // Return hex-encoded SHA256 hash return hash('sha256', $str); } // Exact usage matching your Swift code: $inputStr = "your input text here"; $finalStr = sha256($inputStr);
PHP Equivalent for Raw Binary SHA256 Digest
If you need to replicate the sha256(_ data: Data) method that returns raw binary data instead of a hex string, use this:
function sha256Raw(string $data): string { // Return raw binary SHA256 digest return hash('sha256', $data, true); }
Key Details
- PHP's built-in
hash()function handles the low-level hashing work thatCC_SHA256does in Swift, so no need for external libraries. - The third parameter in
hash()toggles output format:false(default) gives a hex string,truegives raw binary bytes. - The UTF-8 check is optional but included to match Swift's behavior where it returns nil if the string can't be converted to UTF-8 data. If you're confident all inputs are valid UTF-8, you can remove that check to simplify the function.
内容的提问来源于stack exchange,提问作者Ethan Allen
相关产品推荐
相关产品推荐

