Skip to content

Instantly share code, notes, and snippets.

@0xABCCBA
Created August 24, 2018 02:19
Show Gist options
  • Save 0xABCCBA/9d13939ded5cb946b9e6ff79c71d6e2d to your computer and use it in GitHub Desktop.
Save 0xABCCBA/9d13939ded5cb946b9e6ff79c71d6e2d to your computer and use it in GitHub Desktop.
//
// Base64URLUtils.swift
// CodeRepo
//
// Created by tramp on 23/04/2018.
// Copyright © 2018 tramp. All rights reserved.
//
import Foundation
/// 转换base64URL编码的字符串为base64编码的字符串
///
/// - Parameter base64URL: base64URL编码的字符串
/// - Returns: base64编码的字符串
func convertBase64URLToBase64(_ base64URL: String) -> String {
var result = base64URL
.then(from: "-", to: "+")
.then(from: "_", to: "/")
.then(from: "\n", to: "")
.then(from: "\r", to: "")
var equalsToBeAdded = base64URL.count % 4
/// 根据base64编码规则,末尾的=只有0, 1,2三种可能
if equalsToBeAdded > 0 {
if equalsToBeAdded == 3 {
equalsToBeAdded = 1
}
(0..<equalsToBeAdded).forEach{ _ in result.append("=")}
}
return result
}
/// 转换base64编码的字符串为base64URL编码的字符串
///
/// - Parameter base64: base64编码的字符串
/// - Returns: base64URL编码的字符串
func convertBase64ToBase64URL(_ base64: String) -> String {
let result = base64
.then(from: "+", to: "-")
.then(from: "/", to: "_")
.then(from: "=", to: "")
return result
}
extension String {
func then(from: String, to: String) -> String {
return self.replacingOccurrences(of: from, with: to, options: .literal, range: range(of: self))
}
}
@0xABCCBA
Copy link
Author

base64 ⇋ base64URL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment