Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

createCipheriv Returns "Invalid iv" Error #193

Open
baryon opened this issue Oct 11, 2023 · 0 comments
Open

createCipheriv Returns "Invalid iv" Error #193

baryon opened this issue Oct 11, 2023 · 0 comments

Comments

@baryon
Copy link

baryon commented Oct 11, 2023

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.
SCR-20231011-qqts
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant