|
| 1 | +import crypto from "crypto" |
| 2 | +import {BaseWallet, ethers, getBytes, SigningKey, solidityPackedKeccak256} from "ethers" |
| 3 | +import * as fs from "node:fs"; |
| 4 | + |
| 5 | +const block_size = 16 // AES block size in bytes |
| 6 | +const hexBase = 16 |
| 7 | + |
| 8 | +export function encrypt(key: Buffer, plaintext: Buffer): { ciphertext: Buffer; r: Buffer } { |
| 9 | + // Ensure plaintext is smaller than 128 bits (16 bytes) |
| 10 | + if (plaintext.length > block_size) { |
| 11 | + throw new RangeError("Plaintext size must be 128 bits or smaller.") |
| 12 | + } |
| 13 | + // Ensure key size is 128 bits (16 bytes) |
| 14 | + if (key.length != block_size) { |
| 15 | + throw new RangeError("Key size must be 128 bits.") |
| 16 | + } |
| 17 | + // Create a new AES cipher using the provided key |
| 18 | + const cipher = crypto.createCipheriv("aes-128-ecb", key, null) |
| 19 | + |
| 20 | + // Generate a random value 'r' of the same length as the block size |
| 21 | + const r = crypto.randomBytes(block_size) |
| 22 | + |
| 23 | + // Encrypt the random value 'r' using AES in ECB mode |
| 24 | + const encryptedR = cipher.update(r) |
| 25 | + |
| 26 | + // Pad the plaintext with zeros if it's smaller than the block size |
| 27 | + const plaintext_padded = Buffer.concat([Buffer.alloc(block_size - plaintext.length), plaintext]) |
| 28 | + |
| 29 | + // XOR the encrypted random value 'r' with the plaintext to obtain the ciphertext |
| 30 | + const ciphertext = Buffer.alloc(encryptedR.length) |
| 31 | + for (let i = 0; i < encryptedR.length; i++) { |
| 32 | + ciphertext[i] = encryptedR[i] ^ plaintext_padded[i] |
| 33 | + } |
| 34 | + |
| 35 | + return {ciphertext, r} |
| 36 | +} |
| 37 | + |
| 38 | +export function decrypt(key: Buffer, r: Buffer, ciphertext: Buffer): Buffer { |
| 39 | + if (ciphertext.length !== block_size) { |
| 40 | + throw new RangeError("Ciphertext size must be 128 bits.") |
| 41 | + } |
| 42 | + |
| 43 | + // Ensure key size is 128 bits (16 bytes) |
| 44 | + if (key.length != block_size) { |
| 45 | + throw new RangeError("Key size must be 128 bits.") |
| 46 | + } |
| 47 | + |
| 48 | + // Ensure random size is 128 bits (16 bytes) |
| 49 | + if (r.length != block_size) { |
| 50 | + throw new RangeError("Random size must be 128 bits.") |
| 51 | + } |
| 52 | + |
| 53 | + // Create a new AES decipher using the provided key |
| 54 | + const cipher = crypto.createCipheriv("aes-128-ecb", key, null) |
| 55 | + |
| 56 | + // Encrypt the random value 'r' using AES in ECB mode |
| 57 | + const encryptedR = cipher.update(r) |
| 58 | + |
| 59 | + // XOR the encrypted random value 'r' with the ciphertext to obtain the plaintext |
| 60 | + const plaintext = Buffer.alloc(encryptedR.length) |
| 61 | + for (let i = 0; i < encryptedR.length; i++) { |
| 62 | + plaintext[i] = encryptedR[i] ^ ciphertext[i] |
| 63 | + } |
| 64 | + |
| 65 | + return plaintext |
| 66 | +} |
| 67 | + |
| 68 | +export function generateRSAKeyPair(): crypto.KeyPairSyncResult<Buffer, Buffer> { |
| 69 | + // Generate a new RSA key pair |
| 70 | + return crypto.generateKeyPairSync("rsa", { |
| 71 | + modulusLength: 2048, |
| 72 | + publicKeyEncoding: { |
| 73 | + type: "spki", |
| 74 | + format: "der", // Specify 'der' format for binary data |
| 75 | + }, |
| 76 | + privateKeyEncoding: { |
| 77 | + type: "pkcs8", |
| 78 | + format: "der", // Specify 'der' format for binary data |
| 79 | + }, |
| 80 | + }) |
| 81 | +} |
| 82 | + |
| 83 | +export function decryptRSA(privateKey: Buffer, ciphertext: Buffer): Buffer { |
| 84 | + // Load the private key in PEM format |
| 85 | + let privateKeyPEM = privateKey.toString("base64") |
| 86 | + privateKeyPEM = `-----BEGIN PRIVATE KEY-----\n${privateKeyPEM}\n-----END PRIVATE KEY-----` |
| 87 | + // Decrypt the ciphertext using RSA-OAEP |
| 88 | + return crypto.privateDecrypt( |
| 89 | + { |
| 90 | + key: privateKeyPEM, |
| 91 | + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, |
| 92 | + oaepHash: "sha256", |
| 93 | + }, |
| 94 | + ciphertext |
| 95 | + ) |
| 96 | +} |
| 97 | + |
| 98 | + |
| 99 | +export function sign(message: string, privateKey: string) { |
| 100 | + const key = new SigningKey(privateKey) |
| 101 | + const sig = key.sign(message) |
| 102 | + return Buffer.concat([getBytes(sig.r), getBytes(sig.s), getBytes(`0x0${sig.v - 27}`)]) |
| 103 | +} |
| 104 | + |
| 105 | +export function keccak256(publicKey: Buffer) { |
| 106 | + return ethers.keccak256(publicKey); |
| 107 | +} |
| 108 | + |
| 109 | +export function signInputText(sender: { |
| 110 | + wallet: BaseWallet; |
| 111 | + userKey: string |
| 112 | +}, contractAddress: string, functionSelector: string, ct: Buffer) { |
| 113 | + const message = solidityPackedKeccak256( |
| 114 | + ["address", "address", "bytes4", "uint256"], |
| 115 | + [sender.wallet.address, contractAddress, functionSelector, BigInt("0x" + ct.toString("hex"))] |
| 116 | + ) |
| 117 | + |
| 118 | + return sign(message, sender.wallet.privateKey); |
| 119 | +} |
| 120 | + |
| 121 | +export function buildInputText( |
| 122 | + plaintext: bigint, |
| 123 | + sender: { wallet: BaseWallet; userKey: string }, |
| 124 | + contractAddress: string, |
| 125 | + functionSelector: string |
| 126 | +) { |
| 127 | + // Convert the plaintext to bytes |
| 128 | + const plaintextBytes = Buffer.alloc(8) // Allocate a buffer of size 8 bytes |
| 129 | + plaintextBytes.writeBigUInt64BE(plaintext) // Write the uint64 value to the buffer as little-endian |
| 130 | + |
| 131 | + // Encrypt the plaintext using AES key |
| 132 | + const {ciphertext, r} = encrypt(Buffer.from(sender.userKey, "hex"), plaintextBytes) |
| 133 | + const ct = Buffer.concat([ciphertext, r]) |
| 134 | + |
| 135 | + const signature = signInputText(sender, contractAddress, functionSelector, ct); |
| 136 | + |
| 137 | + // Convert the ciphertext to BigInt |
| 138 | + const ctInt = BigInt("0x" + ct.toString("hex")) |
| 139 | + |
| 140 | + return {ctInt, signature} |
| 141 | +} |
| 142 | + |
| 143 | +export async function buildStringInputText( |
| 144 | + plaintext: string, |
| 145 | + sender: { wallet: BaseWallet; userKey: string }, |
| 146 | + contractAddress: string, |
| 147 | + functionSelector: string |
| 148 | +) { |
| 149 | + let encoder = new TextEncoder() |
| 150 | + |
| 151 | + let encodedStr = encoder.encode(plaintext) |
| 152 | + |
| 153 | + let encryptedStr = new Array<{ ciphertext: bigint, signature: Buffer }>(plaintext.length) |
| 154 | + |
| 155 | + for (let i = 0; i < plaintext.length; i++) { |
| 156 | + const {ctInt, signature} = buildInputText(BigInt(encodedStr[i]), sender, contractAddress, functionSelector) |
| 157 | + encryptedStr[i] = {ciphertext: ctInt, signature} |
| 158 | + } |
| 159 | + |
| 160 | + return encryptedStr |
| 161 | +} |
| 162 | + |
| 163 | +export function generateAesKey() { |
| 164 | + return crypto.randomBytes(block_size).toString("hex") |
| 165 | +} |
| 166 | + |
| 167 | +export function loadAesKey(filePath: string): Buffer { |
| 168 | + const hexKey = fs.readFileSync(filePath, 'utf8').trim(); |
| 169 | + const key = Buffer.from(hexKey, 'hex'); |
| 170 | + if (key.length !== block_size) { |
| 171 | + throw new Error(`Invalid key length: ${key.length} bytes, must be ${block_size} bytes`); |
| 172 | + } |
| 173 | + return key; |
| 174 | +} |
| 175 | + |
| 176 | +export function writeAesKey(filePath: string, key: Buffer): void { |
| 177 | + if (key.length !== block_size) { |
| 178 | + throw new Error(`Invalid key length: ${key.length} bytes, must be ${block_size} bytes`); |
| 179 | + } |
| 180 | + const hexKey = key.toString('hex'); |
| 181 | + fs.writeFileSync(filePath, hexKey); |
| 182 | +} |
| 183 | + |
| 184 | + |
0 commit comments