Created
September 13, 2018 16:22
-
-
Save th3m477/eb7bb59ca211b8849c90f4d3c3f8697b to your computer and use it in GitHub Desktop.
Emoji hash example in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func emojiHash(_ input: String) -> String { | |
// HashEmoji.txt is a line separated file of 256 emojis (1 per byte) | |
// https://gist.github.com/th3m477/c0b306fd7992459f366e1a49fe0520d2 | |
guard let path = Bundle.main.path(forResource: "HashEmoji", ofType: "txt"), | |
let emojiData = try? String(contentsOfFile: path, encoding: .utf8) | |
else { | |
preconditionFailure("HashEmoji resource not available") | |
} | |
let emojis = emojiData.components(separatedBy: .newlines) | |
// Convert the input string into bytes and hash | |
// Note for Ethereum Addresses at Argent we use the hex value without leading 0x | |
let data = keccak256(input) | |
var str = "" | |
// Given we use keccak as a hash function, we can simply take the first couple of bytes | |
// to represent the level of uniqueness required (based on probability of collision) | |
for i in 0..<4 { | |
let byte = data.bytes[i] | |
str.append(emojis[Int(byte)]) | |
} | |
return str | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment