Last active
January 11, 2018 15:07
-
-
Save grifas/3f0d02dcbec2f2830675a4592dbd9245 to your computer and use it in GitHub Desktop.
String Extension to get based 64 signature to sign google api urls in swift 3
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
// String Extension to get based 64 signature to sign google api urls in Swift 3 | |
// FROM https://stackoverflow.com/a/20300625/5965126 | |
extension String { | |
func signatureBase64(key: String) -> String? { | |
if let signature = self.data(using: .utf8) as NSData?, let signingKey = self.decodeURLBase64String(string: key) { | |
if let digest = self.hmacSha1(data: signature, key: signingKey) { | |
return self.encodeURLBase64Data(data: digest) | |
} | |
} | |
return nil | |
} | |
func decodeURLBase64String(string: String) -> NSData? { | |
var replacedString = string.replacingOccurrences(of: "-", with: "+") | |
replacedString = string.replacingOccurrences(of: "_", with: "/") | |
if let data = Data(base64Encoded: replacedString) as NSData? { | |
return data | |
} | |
return nil | |
} | |
func encodeURLBase64Data(data: NSData) -> String { | |
var signatureBase64 = data.base64EncodedString(options: []) | |
signatureBase64 = signatureBase64.replacingOccurrences(of: "+", with: "-") | |
signatureBase64 = signatureBase64.replacingOccurrences(of: "/", with: "_") | |
return signatureBase64 | |
} | |
func hmacSha1(data: NSData, key: NSData) -> NSData? { | |
if let hmac: NSMutableData = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH)) { | |
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key.bytes, key.length, data.bytes, data.length, hmac.mutableBytes) | |
return hmac | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment