[Javascript] 一般字串、Base64字串、Binary(uint8 array)轉換: crypto-js與base64-js

crypto-js
https://github.com/brix/crypto-js

base64-js
https://github.com/beatgammit/base64-js

前端utf-8字串通訊時常會需要轉編譯處理,可避免其中的特殊字元或符號,而utf-8字串要轉Base64時通常需要呼叫window.btoa,也不能使用任意字元,得要先行處理例如呼叫encodeURIComponent,而若需要於後端Node.js進行這些工作,這邊推薦可使用CryptoJS來處理utf-8字串正轉反轉成Base64。

而由Base64字串轉至Binary(uint8 array)時可減少傳輸量,也可減少儲存所需體積,但這需要專門處理。過去我自己是常使用base64-js套件處理,後來研究CryptoJS也能替換base64-js。後面程式碼為使用CryptoJS封裝後的轉換函式,給有興趣的朋友自行測試與運用。


以下為單html檔測試範例︰
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>crypto.js & base64.js Convert Demo</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!--使用crypto-js-->
    <!--https://github.com/brix/crypto-js-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

    <!--使用base64-js-->
    <!--https://github.com/beatgammit/base64-js-->
    <script src="https://cdn.jsdelivr.net/npm/base64-js@1.3.0/base64js.min.js"></script>

</head>
<body>

    <div id="app"></div>

    <script>

        function str2b64(str) {
            //utf-8任意字串轉base64字串

            let b64 = window.btoa(unescape(encodeURIComponent(str)))
            return b64
        }

        function cp_str2b64(str) {
            //utf-8任意字串轉base64字串

            let words = CryptoJS.enc.Utf8.parse(str);
            let b64 = CryptoJS.enc.Base64.stringify(words);
            return b64
        }

        function b642str(b64) {
            //base64字串轉回utf-8任意字串

            let str = decodeURIComponent(escape(window.atob(b64)))
            return str
        }

        function cp_b642str(b64) {
            //base64字串轉回utf-8任意字串

            let wa = CryptoJS.enc.Base64.parse(b64);
            let str = wa.toString(CryptoJS.enc.Utf8);
            return str
        }

        function b64tobin(b64) {
            //base64字串轉binary(u8array)

            let bin = base64js.toByteArray(b64)
            return bin
        }

        function cp_b64tobin(b64) {
            //base64字串轉binary(u8array)

            let wa = CryptoJS.enc.Base64.parse(b64)
            let words = wa.words;
            let sigBytes = wa.sigBytes;
            let bin = new Uint8Array(sigBytes);
            for (var i = 0; i < sigBytes; i++) {
                let byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                bin[i] = byte;
            }
            return bin
        }

        function bintob64(bin) {
            //binary(u8array)轉回base64字串

            return base64js.fromByteArray(bin)
        }

        function cp_bintob64(bin) {
            //binary(u8array)轉回base64字串

            let wa = CryptoJS.lib.WordArray.create(bin)
            let b64 = wa.toString(CryptoJS.enc.Base64)
            return b64
        }

        console.log = function (c, v) {
            //覆蓋log, 使用jQuery輸出至網頁
            $('#app').append('<div style="padding:3px;">' + 'log: ' + c + ', ' + v + '</div>')
        }

        let c = 'Hello 中文 はは'

        //utf-8任意字串轉base64字串
        let b64_1 = str2b64(c)
        let b64_2 = cp_str2b64(c)
        console.log('str2b64', b64_1)
        console.log('cp_str2b64', b64_2)
        //SGVsbG8gV29ybGQ=

        //base64字串轉回utf-8任意字串
        let c_1 = b642str(b64_1)
        let c_2 = cp_b642str(b64_2)
        console.log('b642str', c_1)
        console.log('cp_b642str', c_2)
        //Hello World

        //base64字串轉binary(u8array)
        let b_1 = b64tobin(b64_1)
        let b_2 = cp_b64tobin(b64_2)
        console.log('b64tobin', b_1)
        console.log('cp_b64tobin', b_2)
        //Uint8Array(11) [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

        //binary(u8array)轉回base64字串
        let bb64_1 = bintob64(b_1)
        let bb64_2 = cp_bintob64(b_2)
        console.log('bintob64', bb64_1)
        console.log('cp_bintob64', bb64_2)
        //SGVsbG8gV29ybGQ=

    </script>

</body>
</html>


載入後畫面為︰



#Javascript, crypto-js, base64-js, utf-8, string, base64, binary, uint8, array

留言