ADD options to make encryption deterministic

pull/594/head
pubkey 3 years ago
parent 06d2f50b87
commit 04426e525d
  1. 5
      src/encrypt-with-public-key.js
  2. 40
      test/unit.test.js
  3. 6
      typings/index.d.ts

@ -5,7 +5,7 @@ import {
decompress
} from './public-key';
export default function encryptWithPublicKey(publicKey, message) {
export default function encryptWithPublicKey(publicKey, message, opts) {
// ensure its an uncompressed publicKey
publicKey = decompress(publicKey);
@ -16,7 +16,8 @@ export default function encryptWithPublicKey(publicKey, message) {
return encrypt(
Buffer.from(pubString, 'hex'),
Buffer.from(message)
Buffer.from(message),
opts ? opts : {}
).then(encryptedBuffers => {
const encrypted = {
iv: encryptedBuffers.iv.toString('hex'),

@ -2,6 +2,7 @@ const AsyncTestUtil = require('async-test-util');
const assert = require('assert');
const BN = require('bn.js');
const EthCrypto = require('../dist/lib/index');
const crypto = require('crypto');
const TEST_DATA = {
address: '0x3f243FdacE01Cfd9719f7359c94BA11361f32471',
@ -162,6 +163,45 @@ describe('unit.test.js', () => {
);
assert.equal(decrypted, message);
});
it('should use a random iv if none provided', async () => {
const message = AsyncTestUtil.randomString(12);
const encrypted = await EthCrypto.encryptWithPublicKey(
TEST_DATA.publicKey,
message
);
const encrypted2 = await EthCrypto.encryptWithPublicKey(
TEST_DATA.publicKey,
message
);
assert.ok(encrypted.ciphertext !== encrypted2.ciphertext);
});
it('should have deterministic output if iv is provided', async () => {
const message = AsyncTestUtil.randomString(12);
const iv = crypto.randomBytes(16);
const ephemPrivateKey = crypto.randomBytes(32);
console.dir(iv);
const encrypted = await EthCrypto.encryptWithPublicKey(
TEST_DATA.publicKey,
message,
{
iv,
ephemPrivateKey
}
);
const encrypted2 = await EthCrypto.encryptWithPublicKey(
TEST_DATA.publicKey,
message,
{
iv,
ephemPrivateKey
}
);
assert.strictEqual(encrypted.ciphertext, encrypted2.ciphertext);
assert.strictEqual(encrypted.mac, encrypted2.mac);
});
});
describe('negative', () => {
it('should throw when non-key given', async () => {

@ -56,7 +56,11 @@ type vrsType = {
};
export const vrs: vrsType;
type encryptWithPublicKeyType = (publicKey: string, message: string) => Promise<Encrypted>;
export type EncryptOptions = {
iv?: Buffer,
ephemPrivateKey?: Buffer
};
type encryptWithPublicKeyType = (publicKey: string, message: string, options?: EncryptOptions) => Promise<Encrypted>;
export const encryptWithPublicKey: encryptWithPublicKeyType;
type decryptWithPrivateKeyType = (privateKey: string, encrypted: Encrypted) => Promise<string>;

Loading…
Cancel
Save