尝试在
Swift中解码JWT有效负载并且遇到非常困难的时间
static func decodePayload(tokenstr: String) { //splitting JWT to extract payload let arr = split(tokenstr) {$0 == "."} //base64 encoded string i want to decode let base64String = arr[1] as String println(base64String) //eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0 //attempting to convert base64 string to nsdata let nsdata: NSData = NSData(base64EncodedString: base64String,options: NSDataBase64DecodingOptions(rawValue: 0)) //decoding fails because nsdata unwraps as nil let base64Decoded: NSString = NSString(data: nsdata!,encoding: NSUTF8StringEncoding)! }
解决方法
eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0
不是有效的Base64编码字符串,因为它的长度
不是4的倍数.一些Base64解码器容忍这个错误,但是
NSData方法没有.
所以这实际上是服务器端创建的错误
Base64编码的字符串.如有必要,您可以在应用中修复它
通过添加= =字符所需的填充(为Swift 2更新的代码):
var base64String = arr[1] as String if base64String.characters.count % 4 != 0 { let padlen = 4 - base64String.characters.count % 4 base64String += String(count: padlen,repeatedValue: Character("=")) }
现在解码按预期工作:
if let data = NSData(base64EncodedString: base64String,options: []),let str = String(data: data,encoding: NSUTF8StringEncoding) { print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"} }
斯威夫特4:
var base64String = "eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0" if base64String.count % 4 != 0 { let padlen = 4 - base64String.count % 4 base64String.append(contentsOf: repeatElement("=",count: padlen)) } if let data = Data(base64Encoded: base64String),encoding: .utf8) { print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"} }