Skip to content

Instantly share code, notes, and snippets.

@bre7
Last active May 19, 2016 14:45
Show Gist options
  • Save bre7/c2a684e6af5dfc3fd856 to your computer and use it in GitHub Desktop.
Save bre7/c2a684e6af5dfc3fd856 to your computer and use it in GitHub Desktop.
PFUser extension to get hash from user email
import Foundation
import CocoaLumberjack
import Parse.PFUser
extension PFUser {
var hashForEmail: String? {
if let stringValue = self.email {
var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
var data : NSData! = stringValue.dataUsingEncoding(NSUTF8StringEncoding)
// Confirm that the length of the user name is small enough
// to be recast when calling the hash function.
if data.length > Int.max {
DDLogError("Account name too long to hash: \(stringValue)")
return .None
}
CC_SHA256(data.bytes,
CC_LONG(data.length),
&hash)
// Convert the array of bytes into a string showing its hex representation.
var userAccountHash = NSMutableString()
for i in 0..<Int(CC_SHA256_DIGEST_LENGTH) {
// Add a dash every four bytes, for readability.
if i != 0 && i%4 == 0 {
userAccountHash.appendString("-")
}
userAccountHash.appendFormat("%02x", hash[i])
}
return String(userAccountHash)
} else {
return .None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment