需要帮助将此PHP sha256散列码转换为swift(iOS)

时间:2015-03-13 14:16:20

标签: php ios swift hash sha256

我需要将这些PHP代码转换为swift来创建哈希,我在PHP中使用哈希模式用SHA256哈希2个字符串,我想在swift,任何想法中做到这一点? SELF :: SECRET是一个密钥,SELF :: HASH_PATTERN是我的模式,看起来像这样:" 00101010011100001010"

public function hash($first, $second) {
    // Append the secret to the values.
    $first = self::SECRET . $first;
    $second = $second . self::SECRET;

    // Hash the values.
    $hash = hash_init('sha256');
    hash_update($hash, $first);
    $hash1 = hash_final($hash);
    $hash = hash_init('sha256');
    hash_update($hash, $second);
    $hash2 = hash_final($hash);

    // Create a new hash with pieces of the two we just made.
    $result = '';
    for ($i = 0; $i < strlen(self::HASH_PATTERN); $i++) {
        $result .= substr(self::HASH_PATTERN, $i, 1) ? $hash2[$i] : $hash1[$i];
    }

    return $result;
}

谢谢!

更新:     这是我无法弄清楚的部分:

    $hash = hash_init('sha256');
    hash_update($hash, $first);
    $hash1 = hash_final($hash);

更新:

经过几个小时的研究和编码后,我终于明白了。 这是我写的代码,也许不是最好的,但它的工作原理:) 我使用github中的一个小类在swift中生成SHA256字符串,称为NSHash

func create_token(first:String, second:String) -> String {

    var newFirst = constants.secret + first as NSString
    var newSecond = second + constants.secret as NSString

    var hash1 = newFirst.SHA256()
    var hash2 = newSecond.SHA256()

    var result = ""

    for var i = 0; i < countElements(constants.hash_pattern); i++ {

        var character = "\(constants.hash_pattern[i])" as String
        var number:Int = character.toInt()!

        if number == 1 {

            result = "\(result)\(hash2[i])"


        }else {
            result = "\(result)\(hash1[i])"

        }

     }

    return result
}

0 个答案:

没有答案
相关问题