尝试在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)!
}
答案 0 :(得分:21)
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"}
}
Swift 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) ,
let str = String(data: data, encoding: .utf8) {
print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}
}
答案 1 :(得分:4)
以上解决方案对我有用,我转换为swift3
在这里你可以找到swift3代码
var base64Str = arr[1] as String
if base64Str.characters.count % 4 != 0 {
let padlen = 4 - base64Str.characters.count % 4
base64Str += String(repeating: "=", count: padlen)
}
if let data = Data(base64Encoded: base64Str, options: []),
let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
答案 2 :(得分:-1)
Swift 4如下:
if let data = Data(base64Encoded: base64String, options: []),
let str = String(data: data as Data, encoding: String.Encoding.utf8) {
print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}
}