Skip to content

Instantly share code, notes, and snippets.

@Breta01
Last active March 11, 2022 14:58
Show Gist options
  • Save Breta01/da66e5f518f9866f50fafdc07a08ac40 to your computer and use it in GitHub Desktop.
Save Breta01/da66e5f518f9866f50fafdc07a08ac40 to your computer and use it in GitHub Desktop.
Encryption function used by FELToken
import { encrypt } from '@metamask/eth-sig-util';
const ascii85 = require('ascii85');
function encryptData(publicKey: Buffer, data: Buffer): number[] {
// Returned object contains 4 properties: version, ephemPublicKey, nonce, ciphertext
// Each contains data encoded using base64, version is always the same string
const enc = encrypt({
publicKey: publicKey.toString('base64'),
data: ascii85.encode(data).toString(),
version: 'x25519-xsalsa20-poly1305',
});
// We want to store the data in smart contract, therefore we concatenate them
// into single Buffer
const buf = Buffer.concat([
Buffer.from(enc.ephemPublicKey, 'base64'),
Buffer.from(enc.nonce, 'base64'),
Buffer.from(enc.ciphertext, 'base64'),
]);
// In smart contract we are using `bytes[112]` variable (fixed size byte array)
// you might need to use `bytes` type for dynamic sized array
// We are also using ethers.js which requires type `number[]` when passing data
// for argument of type `bytes` to the smart contract function
// Next line just converts the buffer to `number[]` required by contract function
// THIS LINE IS USED IN OUR ORIGINAL CODE:
// return buf.toJSON().data;
// Return just the Buffer to make the function directly compatible with decryptData function
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment