首页 > 解决方案 > 为什么ballerina不提供base64编解码只提供base64URL编解码

问题描述

我注意到芭蕾舞女演员编码包没有 encodeBase64/decodeBase64 的方法,而是有 encodeBase64URL/decodeBase64URL。

当我使用它并使用其他 base64 编码库时,结果不一样

标签: ballerina

解决方案


base64 编码 [1] 和 base64 URL 编码 [2] 是不同的。Ballerina 从语言本身提供 base64 编码/解码 API。您可以使用ballerina/encoding模块进行 base64 URL 编码/解码。

import ballerina/io;

public function main() {
    string input = "Hello Ballerina!";
    byte[] inputArr = input.toBytes();
    string encodedString = inputArr.toBase64();
    io:println(encodedString);
}

有关更多示例,请参阅加密 BBE [3]。

[1] https://www.rfc-editor.org/rfc/rfc4648#section-4

[2] https://www.rfc-editor.org/rfc/rfc4648#section-5

[3] https://ballerina.io/v1-1/learn/by-example/crypto.html


[更新] base64 编码/解码示例。

import ballerina/io;
import ballerina/lang.'array as arr;
import ballerina/lang.'string as str;

public function main() returns error? {
    string input = "Hello Ballerina!";
    byte[] inputArr = input.toBytes();
    string encodedString = inputArr.toBase64();
    io:println(encodedString);

    byte[] decoded = check arr:fromBase64(encodedString);
    string decodedString = check str:fromBytes(decoded);
    io:println(decodedString);
}

推荐阅读