You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 that CC_SHA256 does in Swift, so no need for external libraries.
  • The third parameter in hash() toggles output format: false (default) gives a hex string, true gives 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:14:00