Skip to content

Instantly share code, notes, and snippets.

@Breta01
Last active March 11, 2022 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Breta01/bc961d8b44d8ae2125c37306b3330da7 to your computer and use it in GitHub Desktop.
Save Breta01/bc961d8b44d8ae2125c37306b3330da7 to your computer and use it in GitHub Desktop.
Decrypting data with MetaMas
const ascii85 = require('ascii85');
async function decryptData(account: string, data: Buffer): Promise<Buffer> {
// Reconstructing the original object outputed by encryption
const structuredData = {
version: 'x25519-xsalsa20-poly1305',
ephemPublicKey: data.slice(0, 32).toString('base64'),
nonce: data.slice(32, 56).toString('base64'),
ciphertext: data.slice(56).toString('base64'),
};
// Convert data to hex string required by MetaMask
const ct = `0x${Buffer.from(JSON.stringify(structuredData), 'utf8').toString('hex')}`;
// Send request to MetaMask to decrypt the ciphertext
// Once again application must have acces to the account
const decrypt = await window.ethereum.request({
method: 'eth_decrypt',
params: [ct, account],
});
// Decode the base85 to final bytes
return ascii85.decode(decrypt);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment