如何知道文本编码方案以便我可以将字节解码为字符串

How to know the text encoding scheme so that I can decode the bytes to a string

我正在使用 Chrome 浏览器的 crypto.SubCrypto API。我在其中生成一个 PSA-PSS 密钥并想导出该密钥:

let key = await window.crypto.subtle.generateKey(
  {
    name: "RSA-PSS",
    modulusLength: 2048,
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
    hash: "SHA-256",
  },
  true, 
  ["sign", "verify"] 
);

let exported_key = await window.crypto.subtle.exportKey("spki", key.publicKey);

let export_key_buffer = new Uint8Array(exported_key); // convert the key from an ArrayBuffer to a TypedArray

// Convert export_key_buffer into a string
const decoder = new TextDecoder();
let string_key = decoder.decode(export_key_buffer)
console.log(string_key). // unreadable text

基本上,我用 generateKey() and then export it with exportKey(). The exportKey returns an ArrayBuffer and I want to turn that into a string, so I follow an answer here, which uses TextDecoder 生成一个密钥。但是 TextDecoderexported_key_buffer 解码为不可读的字符串:

0�"0
    *�H��
�0�
��<FY�d!��Ø+�XM]�A�/�ݔM�pRZ���[��&5�-���w]@��^�e
�����~����eq�Y^�
��EѮf�8v��z{(���GF
�x�;�����N?eP�Xe���D�C ��C4+��}?�|/Oj:u�q�j�
�q�-z�����r+�+˫��x3T�V������oQTS��EA?��yY�J��
�M��8o�L��MND�u��2�ks�=�{G��c�6e��]8

我认为这是因为字节没有uft8编码(TextDecoder的默认解码方案是utf8)?如何找到正确的解码方案?

我对文字不熟悉encoding/decoding,感谢您的帮助。

感谢@cyberbrain。

正如他所说,exported_key 不是文本而是二进制数组。所以如果我想把它转换成文本,我可以使用 base64 编码:

function arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

let base64key = arrayBufferToBase64(exported_key)

那么你就有了这样一个 ASCII 字符串

IIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsep59DiyKMh3v1INHvBtoIrZgv9Vw3bvc6Ttr0DMAChSpmPdnssUsbs3mESKCDY ...