dongxie45083 2019-04-17 21:32
浏览 335
已采纳

Go和Node.js base64编码,解码问题

I am base64 encoding a string in Go

Then decoding in javascript (I have tried 3 different methods)

I cannot get the javascript result to match the original Go string

Go (encode)

a := []byte {138,143,163,224,178,73,161,15,240,121,53,192,198,182,52,245}
fmt.Println("a", string(a), a, len(a))
b := base64.StdEncoding.EncodeToString(a)
fmt.Println("b", b, []byte(b), len([]byte(b)))

js (decode)

 const b = [105,111,43,106,52,76,74,74,111,81,47,119,101,84,88,65,120,114,89,48,57,81,61,61];
 let bString = aesjs.utils.utf8.fromBytes(b);
 console.log("b", bString, b, b.length);

 let a1String = atob(bString);
 let a2String = Base64.decode(bString);
 let a3String = Buffer.from(bString, 'base64').toString('utf8');
 let a1 = aesjs.utils.utf8.toBytes(a1String);
 let a2 = aesjs.utils.utf8.toBytes(a2String);
 let a3 = aesjs.utils.utf8.toBytes(a3String);
 console.log("a", a1, a1.length, a2, a2.length, a3, a3.length);

All 3 methods fail, i.e. a1 != a, a2 != a, a3 != a

I assumed base64 encoding/decoding would be simple

What am I missing? Thanks

EDIT: The js code had a 'typo' - but the problem remains, that ai != a, even a1 != a2 == a3

EDIT: If the original a is simple, then everything works. But when a contains non-printable chars, I cannot decode in js Example where it works: a := []byte {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65} Here it does not works: a := []byte {138, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}

  • 写回答

2条回答 默认 最新

  • duanmei2805 2019-04-18 04:26
    关注

    In Go, strings are UTF8:

    in := "Good afternoon, or こんにちは"
    buf := []byte(in)
    str := base64.StdEncoding.EncodeToString(buf)
    fmt.Println(str)
    

    That prints the base64 encoded (ASCII safe) representation: R29vZCBhZnRlcm5vb24sIG9yIOOBk+OCk+OBq+OBoeOBrw==

    JS strings are UTF-16. So you need to both decode from base64 and convert from utf8 to utf-16. You could use a library, or a helper function, for example:

    function b64DecodeUnicode(str) {
        return decodeURIComponent(atob(str).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
    
    var str = "R29vZCBhZnRlcm5vb24sIG9yIOOBk+OCk+OBq+OBoeOBrw==";
    var result = b64DecodeUnicode(str);
    "Good afternoon, or こんにちは"
    

    The b64DecodeUnicode() function is copied from this answer, see also the link to MDN for detailed info.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog