将 base64URL 解码为 base64 -- Swift

Decode base64URL to base64 -- Swift(将 base64URL 解码为 base64 -- Swift)
本文介绍了将 base64URL 解码为 base64 -- Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有找到正确的方法来快速将 base64URL 解码为 base64 格式.

I haven't found properly way how to decode base64URL to base64 format in swift.

根据base64url转base64 hJQWHABDBjoPHorYF5xghQ(base64URL)应该是 hJQWHABDBjoPHorYF5xghQ==(base64).这里可能会有更多差异.

According to base64url to base64 hJQWHABDBjoPHorYF5xghQ(base64URL) should be hJQWHABDBjoPHorYF5xghQ==(base64). Here could be more differences.

stackoverflow 上没有解决方案.

There are no solutions on stackoverflow.

推荐答案

base64url"与标准Base64编码有两个不同:

"base64url" differs from the standard Base64 encoding in two aspects:

  • 索引 62 和 63 使用不同的字符(-_+/)
  • 没有强制填充 = 字符来使字符串长度四的倍数.
  • different characters are used for index 62 and 63 (- and _ instead of + and /)
  • no mandatory padding with = characters to make the string length a multiple of four.

(比较 https://en.wikipedia.org/wiki/Base64#Variants_summary_table).

这是一个可能的转换函数:

Here is a possible conversion function:

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>
}

为了完整起见,这将是相反的转换:

For the sake of completeness, this would be the opposite conversion:

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
}

这篇关于将 base64URL 解码为 base64 -- Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)