一尘不染

在Swift中解码JSON Web令牌

swift

试图在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)!


}

阅读 195

收藏
2020-07-07

共1个答案

一尘不染

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) ,
    let str = String(data: data, encoding: .utf8) {
    print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}
}
2020-07-07