解码.utf8可能无法迅速有效吗?

时间:2018-07-02 14:02:05

标签: ios swift utf-8 encode

这是我的字符串扩展名

extension String {

    func base64Encoded() -> String? {
        return data(using: .utf8)?.base64EncodedString()
    }

    func base64Decoded() -> String? {
        guard let data = Data(base64Encoded: self) else { return nil }
        return String(data: data, encoding: .utf8)
    } 
}

我尝试解码字符串

eyJhdWQiOiIxMjM0IiwiaWF0IjoxNTMwNTM3MzQxLCJleHAiOjE1MzA1NDA5NDEsImlzcyI6Imh0dHA6Ly82O1282Dcu2jgzL2E32ko2N2ciLCJzdWIiOiIwMUNGVjZaRjA3WkhKQ1FZQVRURDFOVkM0UCIsInJscyI6WyJjb2FjaC5kcml2ZXIiXX0

{
  "aud": "1234",
  "iat": 1530537341,
  "exp": 1530540941,
  "iss": "http://6;]��7.�83/a7�J67g",
  "sub": "01CFV6ZF07ZHJCQYATTD1NVC4P",
  "rls": [
    "coach.driver"
  ]
}

但是我还没有实现。关于此主题的最奇怪的事情是,在在线编码/解码转换器网站上,它被转换为true。但是我不能迅速做到这一点。

1 个答案:

答案 0 :(得分:1)

您应该使用URl安全编码和解码

extension String {
  //: ### Base64 encoding a string
  func base64Encoded() -> String? {
    if let data = self.data(using: .utf8) {
      return data.base64URLEncodedString()
    }
    return nil
  }

  //: ### Base64 decoding a string
  func base64Decoded() -> String? {


    if let data = Data(base64URLEncoded: self) {
      return String(data: data, encoding: .utf8)
    }



    return nil
  }
}
extension Data {

  init?(base64URLEncoded string: String) {
    let base64Encoded = string
      .replacingOccurrences(of: "_", with: "/")
      .replacingOccurrences(of: "-", with: "+")
    // iOS can't handle base64 encoding without padding. Add manually
    let padLength = (4 - (base64Encoded.count % 4)) % 4
    let base64EncodedWithPadding = base64Encoded + String(repeating: "=", count: padLength)
    self.init(base64Encoded: base64EncodedWithPadding)
  }

  func base64URLEncodedString() -> String {
    // use URL safe encoding and remove padding
    return self.base64EncodedString()
      .replacingOccurrences(of: "/", with: "_")
      .replacingOccurrences(of: "+", with: "-")
      .replacingOccurrences(of: "=", with: "")
  }
}