I need to convert this pice of PHP code to swift to create hashes, I am using a hash pattern in PHP to hash 2 strings with SHA256 and I would like to do this in swift, any ideas? The SELF::SECRET is a secret key, and the SELF::HASH_PATTERN is my pattern and looks something like this: "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;
}
Thanks!
UPDATE: This is the part which I can't figure out:
$hash = hash_init('sha256');
hash_update($hash, $first);
$hash1 = hash_final($hash);
UPDATE:
After a few hours of doing research and coding I finally got it figured out. This is the code that I wrote, maybe not the best, but it works :) I used a small class from github for generating SHA256 strings in swift called 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
}