Skip to content
Advertisement

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

I’m using Chrome Browser’s crypto.SubCrypto API. I generate a PSA-PSS key in it and want to export the key:

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

Basically, I generate a key with 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. But the TextDecoder decodes the exported_key_buffer into unreadable string:

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

I think this is because the bytes are not uft8 encoded (the default decoding scheme of TextDecoder is utf8)? How can I find out the right decoding scheme?

I am not familiar with text encoding/decoding and I appreciate your help.

Answer

Thanks to @cyberbrain.

Like what he said the exported_key is not a text but a binary array. So if I want to convert it to text, I could use base64 encoding:

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)

Then you have an ASCII string like this

IIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsep59DiyKMh3v1INHvBtoIrZgv9Vw3bvc6Ttr0DMAChSpmPdnssUsbs3mESKCDY ...
Advertisement