如何在JavaScript中实现Base64.getDecoder().decode(nonceBase64Encoded)?

How to achieve Base64.getDecoder().decode(nonceBase64Encoded) in JavaScript?

我有一些用 java 编写的代码,我想将其转换为 JavaScript。

String nonceBase64Encoded = "+8GorZIWoF7mnZ2/M86/eA==";    
byte[] decodednoncebytes = Base64.getDecoder().decode(nonceBase64Encoded);

关于这个解码():

Decodes a Base64 encoded String into a newly-allocated byte arrayusing the Base64 encoding scheme.

An invocation of this method has exactly the same effect as invoking decode(src.getBytes(StandardCharsets.ISO_8859_1))

The atob() function decodes a string of data which has been encoded using Base64 encoding. read more

示例:

var decodedData = atob(encodedData);

The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a String object in which each character in the string is treated as a byte of binary data). read more

示例:

var encodedData = btoa(stringToEncode);

如果您想将字符串转换为字节数组,则可以使用 TextEncoder

new TextEncoder().encode(str)

或者可以使用这个函数:

function stringToByteArray(s){

    // Otherwise, fall back to 7-bit ASCII only
    var result = new Uint8Array(s.length);
    for (var i=0; i<s.length; i++){
        result[i] = s.charCodeAt(i);/* w ww. ja  v  a 2s . co  m*/
    }
    return result;
}