我没有找到正确的方法如何快速将base64URL解码为base64格式。
根据base64url到base64 hJQWHABDBjoPHorYF5xghQ(base64URL)应该是hJQWHABDBjoPHorYF5xghQ==(base64)。这里可能会有更多差异。
hJQWHABDBjoPHorYF5xghQ
hJQWHABDBjoPHorYF5xghQ==
没有关于stackoverflow的解决方案。
“ base64url”在两个方面与标准Base64编码不同:
-
_
+
/
=
(请比较https://en.wikipedia.org/wiki/Base64#Variants_summary_table)。
这是一个可能的转换函数:
func base64urlToBase64(base64url: String) -> String { var base64 = base64url .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") if base64.characters.count % 4 != 0 { base64.append(String(repeating: "=", count: 4 - base64.characters.count % 4)) } return base64 }
例:
let base64url = "hJQWHABDBjoPHorYF5xghQ" let base64 = base64urlToBase64(base64url: base64url) print(base64) // hJQWHABDBjoPHorYF5xghQ== if let data = Data(base64Encoded: base64) { print(data as NSData) // <8494161c 0043063a 0f1e8ad8 179c6085> }
为了完整起见,这将是相反的转换:
func base64ToBase64url(base64: String) -> String { let base64url = base64 .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") return base64url }
Swift 4更新:
func base64urlToBase64(base64url: String) -> String { var base64 = base64url .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") if base64.count % 4 != 0 { base64.append(String(repeating: "=", count: 4 - base64.count % 4)) } return base64 }