react-native-quick-crypto
react-native-quick-crypto copied to clipboard
createCipheriv Returns "Invalid iv" Error
I'm creating a standard Electrum ECDH encryption algorithm.
I encounter an error when using the createCipheriv function. However, there are no issues when using Node.js or react-native-crypto.
Could you take a look at the reason? If you need test code, you can refer to the example below. The bsv library is required and can be installed using
npm install [email protected].
import crypto from "react-native-quick-crypto";
import bsv from "bsv";
const PrivateKey = bsv.PrivateKey;
const PublicKey = bsv.PublicKey;
const Hash = bsv.crypto.Hash;
function electrumECDHKey(publicKey, privateKey) {
// Get ECDH Key
const buf = PublicKey(publicKey.point.mul(privateKey.bn)).toBuffer();
return Hash.sha512(buf);
}
function encrypt(message: string, publicKey: string, privateKey?: string) {
// Prepare keys
const recvPubkey = new PublicKey(publicKey);
// Override ephemeral_key if privateKey is given. This overriding is for traditional ECIES.
const ephemeralKey = new PrivateKey(privateKey);
const ecdhKey = electrumECDHKey(recvPubkey, ephemeralKey);
const iv = ecdhKey.subarray(0, 16);
const keyE = ecdhKey.subarray(16, 32);
const keyM = ecdhKey.subarray(32, 64);
// Encrypt with AES-128-CBC
const cipher = crypto.createCipheriv("aes-128-cbc", keyE, iv);
let crypted = cipher.update(message, "utf8", "binary");
crypted += cipher.final("binary");
// Build Encrypted Massage
const ephemeralPubkey = ephemeralKey.toPublicKey().toBuffer();
const encrypted = Buffer.concat([
Buffer.from("BIE1"),
ephemeralPubkey,
Buffer.from(crypted, "binary"),
]);
const hmac = Hash.sha256hmac(Buffer.from(encrypted), Buffer.from(keyM));
return Buffer.concat([encrypted, hmac]);
}
encrypt("Hello World", new PrivateKey().publicKey)