Comment on page
Decrypting Outputs
fhevmJS example
const decrypt = async (input: number): Uint8Array => {
const instance = fhevmjs.createInstance({
chainId: 5432,
publicKey: tfhePublicKey,
});
const { token, publicKey } = await instance.generateToken({
verifyingContract: contractAddress
});
const params = [userAddress, JSON.stringify(generatedToken.token)];
const sign = await window.ethereum.request({
method: 'eth_signTypedData_v4', params
});
const response = await contract.balanceOf(token.publicKey, sign);
instance.decrypt(contractAddress, response)
}
JavaScript
Python
import * as ethers from 'ethers';
const _sodium = require('libsodium-wrappers');
const generateKey = async () => {
await _sodium.ready;
const sodium = _sodium;
// Generate a new key pair
const keypair = sodium.crypto_box_keypair();
const privateKeyHex = toHexString(keypair.privateKey);
const publicKeyHex = toHexString(keypair.publicKey);
// Return the keys as hexadecimal strings
return { privateKey: privateKeyHex, publicKey: publicKeyHex };
}
const decrypt = async (encryptedHex, secretKeyHex) => {
await _sodium.ready;
const sodium = _sodium;
// Convert encrypted message and secret key from hex to bytes
const encryptedBytes = fromHexString(encryptedHex);
const secretKeyBytes = fromHexString(secretKeyHex);
// Generate publicKey from secretKey
const publicKeyBytes = sodium.crypto_scalarmult_base(secretKeyBytes);
let plaintextBytes;
try {
plaintextBytes = sodium.crypto_box_seal_open(encryptedBytes, publicKeyBytes, secretKeyBytes);
} catch (e) {
// for example, if we want to return 0 as the default value
console.error(e);
return ethers.BigNumber.from(0);
}
// Interpret the plaintext bytes as a big-endian integer
const plaintext = ethers.BigNumber.from(plaintextBytes.reverse());
return plaintext;
}
// helper functions
const fromHexString = (hexString) => {
const arr = hexString.replace(/^(0x)/, '').match(/.{1,2}/g);
return new Uint8Array(arr ? arr.map((byte) => parseInt(byte, 16)) : []);
}
const toHexString = (byteArray) => {
return Array.from(byteArray, byte => ('0' + (byte & 0xFF).toString(16)).slice(-2)).join('');
}
import nacl.utils
from nacl.public import PrivateKey, SealedBox
# generate keys
def generate_key():
sk = PrivateKey.generate()
pk = skbob.public_key
def decrypt(encrypted: bytes, secret_key: str) -> int:
key_bytes = nacl.encoding.HexEncoder.decode(secret_key)
sk = PrivateKey(key_bytes)
pk = skbob.public_key
unseal_box = SealedBox(sk)
plaintext_bytes = unseal_box.decrypt(encrypted)
# Interpret the plaintext bytes as a big-endian integer
plaintext = int.from_bytes(plaintext_bytes, byteorder='big')
return plaintext
Last modified 4mo ago