Decrypt User ID

Get encrypted user id from web.js (EVM-based) or web.js (Solana). The user id is encrypted by AES (CBC).

var aesjs = require('aes-js');

// The aes key provided by blocto, and make sure it is stored in somewhere safe.
var key = aesjs.utils.hex.toBytes('71500f4803c54fcf9445a09e3434afce7552d9916bce4480e54c48a246be3f05');

// The encrypted data from blocto web3 provider.
var ivAndEncryptedData = aesjs.utils.hex.toBytes('3b28cd5be9629b777392e968fef4b0e9ea2715b4f9966ddbfa4dab41b6468a0c30476c6d1e4f58d1b22c9877eaf8bf626dc4f3f10932208684235927b28a2cd85d5aea5595fcd0618019fe80a1afd35c');

var iv = ivAndEncryptedData.slice(0, 16);
var encryptedBytes = ivAndEncryptedData.slice(16);

var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
var paddedDecryptedBytes = aesCbc.decrypt(encryptedBytes);

let res = unpad(paddedDecryptedBytes);
if (res.err) {
    throw res.err
}

console.log(JSON.parse(ab2str(res.unpaddedBytes)));
// `{ user_id: '79efdb10-64dd-436a-9ec9-6bfda8c36e1d' }` is expected
// Store the `user_id` and make some mapping according to your application. 

function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function unpad(decryptedBytes) {
    let paddedLen = decryptedBytes.length;
    if (paddedLen === 0) {
        return {
            unpaddedBytes: null,
            err: new Error('invalid padding size'),
        }
    }

    let padLen = decryptedBytes[paddedLen - 1];
    if (padLen > paddedLen || padLen > 16) {
        return {
            unpaddedBytes: null,
            err: new Error('invalid padding size'),
        }
    }

    for (let i = paddedLen - padLen; i < decryptedBytes.length; i++) {
        if (decryptedBytes[i] !== padLen) {
            return {
                unpaddedBytes: null,
                err: new Error('invalid padding'),
            }
        }
    }

    return {
        unpaddedBytes: decryptedBytes.slice(0, paddedLen - padLen),
        err: null,
    }
}

Last updated