Created
April 28, 2019 20:07
-
-
Save Gurpartap/b6b7f1af707843f599e6c9d76e4c2fff to your computer and use it in GitHub Desktop.
Swift port of Apple's one-way hashing function for setting SKMutablePayment's applicationUsername
This file contains hidden or 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
// Objective-C version available here: | |
// https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/RequestPayment.html#//apple_ref/doc/uid/TP40008267-CH4-SW6 | |
// Usage: | |
// | |
// let userID = "146001" | |
// print(hashedValueForAccountName(userID)) | |
// | |
// Output: | |
// | |
// b0f66adc-83641586-65686681-3fd9dd0b-8ebb6379-6075661b-a45d1aa8-089e1d44 | |
// Custom method to calculate the SHA-256 hash using Common Crypto | |
func hashedValueForAccountName(_ userAccountName: String) -> String? { | |
let HASH_SIZE = Int(32) | |
let hashedChars = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: HASH_SIZE) | |
let accountName = UnsafePointer<CChar>(userAccountName.cString(using: .utf8)) | |
let accountNameLen = userAccountName.count | |
// Confirm that the length of the user name is small enough | |
// to be recast when calling the hash function. | |
if accountNameLen > UInt32.max { | |
print("Account name too long to hash: \(userAccountName)") | |
return nil | |
} | |
CC_SHA256(accountName, CC_LONG(accountNameLen), hashedChars) | |
// Convert the array of bytes into a string showing its hex representation. | |
var userAccountHash = String() | |
for i in 0..<HASH_SIZE { | |
// Add a dash every four bytes, for readability. | |
if (i != 0 && i%4 == 0) { | |
userAccountHash += "-" | |
} | |
userAccountHash += String(format: "%02x", arguments: [hashedChars[i]]) | |
} | |
return userAccountHash | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment