DEV Community

Sufiyan
Sufiyan

Posted on

Generating a non-random UUID, using a hash of multiple strings in Swift

I was just working with some messy data, and realized I need a deterministic way to generate UUIDs from 2 strings in an iOS project. Looks like the only standard method available is

UUID(uuidString: String)

The problem with this is sometimes we don't have the formatted uuidString, so turns out we need to build it ourselves.

Enough talk, here's the code:

import Foundation
import CommonCrypto

func createHash(from string1: String, and string2: String) -> Data {
    let concatenatedString = string1 + string2
    guard let data = concatenatedString.data(using: .utf8) else {
        return Data()
    }

    var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
    _ = data.withUnsafeBytes {
        CC_SHA256($0.baseAddress, UInt32(data.count), &digest)
    }

    return Data(digest)
}

func generateNonRandomUUID(from string1: String, and string2: String) -> UUID {
    let hashData = createHash(from: string1, and: string2)

    // Truncate the hash data to 128 bits (16 bytes)
    let truncatedHashData = hashData.prefix(16)

    // Create a byte array (UnsafePointer<UInt8>) from the truncated hash data
    var byteArray: [UInt8] = []
    truncatedHashData.withUnsafeBytes {
        byteArray.append(contentsOf: $0)
    }

    // Create a UUID from the byte array
    let uuid = NSUUID(uuidBytes: byteArray)

    return uuid as UUID
}
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Top comments (0)