Last active
March 11, 2022 15:04
-
-
Save Breta01/bc961d8b44d8ae2125c37306b3330da7 to your computer and use it in GitHub Desktop.
Decrypting data with MetaMas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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