-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecies.js
More file actions
169 lines (143 loc) · 5.48 KB
/
ecies.js
File metadata and controls
169 lines (143 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import crypto from "crypto";
import secp256k1 from "secp256k1";
/**
* Derive a shared secret using ECDH (Elliptic Curve Diffie-Hellman)
* @param {Buffer} privateKey - Your private key
* @param {Buffer} publicKey - Other party's public key
* @returns {Buffer} Shared secret
*/
function deriveSharedSecret(privateKey, publicKey) {
// Use Node.js built-in ECDH for proper elliptic curve operations
const ecdh = crypto.createECDH("secp256k1");
ecdh.setPrivateKey(privateKey);
// Convert public key to uncompressed format if compressed
let pubKeyForECDH = publicKey;
if (publicKey.length === 33) {
// Convert compressed to uncompressed
pubKeyForECDH = Buffer.from(
secp256k1.publicKeyConvert(new Uint8Array(publicKey), false)
);
}
// Compute shared secret
const sharedSecret = ecdh.computeSecret(pubKeyForECDH);
return sharedSecret.slice(0, 32); // Use first 32 bytes as shared secret
}
/**
* Key derivation function using HKDF
* @param {Buffer} sharedSecret - Shared secret from ECDH
* @param {Buffer} salt - Salt for key derivation
* @param {string} info - Info parameter for HKDF
* @param {number} keyLength - Desired key length
* @returns {Buffer} Derived key
*/
function hkdf(sharedSecret, salt, info, keyLength) {
const infoBuffer = Buffer.from(info, "utf8");
const prk = crypto.createHmac("sha256", salt).update(sharedSecret).digest();
let okm = Buffer.alloc(0);
let counter = 1;
while (okm.length < keyLength) {
const hmac = crypto.createHmac("sha256", prk);
hmac.update(infoBuffer);
hmac.update(Buffer.from([counter]));
okm = Buffer.concat([okm, hmac.digest()]);
counter++;
}
return okm.slice(0, keyLength);
}
/**
* Encrypt a message using ECIES (Elliptic Curve Integrated Encryption Scheme)
* @param {string|Buffer} message - Message to encrypt
* @param {string|Buffer} receiverPublicKey - Receiver's public key
* @returns {Object} Encrypted message object
*/
export function encryptMessage(message, receiverPublicKey) {
// Convert inputs to buffers
const messageBuffer =
typeof message === "string" ? Buffer.from(message, "utf8") : message;
const pubKeyBuffer = importPublicKey(receiverPublicKey);
// Generate ephemeral keypair
const ephemeralKeypair = generateKeypair();
// Derive shared secret using ECDH
const sharedSecret = deriveSharedSecret(
ephemeralKeypair.privateKey,
pubKeyBuffer
);
// Generate random salt and IV
const salt = crypto.randomBytes(16);
const iv = crypto.randomBytes(16);
// Derive encryption and MAC keys using HKDF
const derivedKeys = hkdf(sharedSecret, salt, "ECIES-encryption", 64);
const encryptionKey = derivedKeys.slice(0, 32); // 256-bit AES key
const macKey = derivedKeys.slice(32, 64); // 256-bit HMAC key
// Encrypt message using AES-256-CBC
const cipher = crypto.createCipheriv("aes-256-cbc", encryptionKey, iv);
let encrypted = cipher.update(messageBuffer);
encrypted = Buffer.concat([encrypted, cipher.final()]);
// Create data to authenticate
const dataToAuth = Buffer.concat([
ephemeralKeypair.publicKey,
salt,
iv,
encrypted,
]);
// Generate HMAC for authentication
const mac = crypto.createHmac("sha256", macKey).update(dataToAuth).digest();
return {
ephemeralPublicKey: ephemeralKeypair.publicKeyHex,
salt: salt.toString("hex"),
iv: iv.toString("hex"),
encrypted: encrypted.toString("hex"),
mac: mac.toString("hex"),
};
}
/**
* Decrypt a message using ECIES
* @param {Object} encryptedMessage - Encrypted message object
* @param {string|Buffer} receiverPrivateKey - Receiver's private key
* @returns {Buffer} Decrypted message as Buffer (use .toString('utf8') for text)
*/
export function decryptMessage(encryptedMessage, receiverPrivateKey) {
// Convert private key to buffer
const privKeyBuffer =
typeof receiverPrivateKey === "string"
? Buffer.from(receiverPrivateKey, "hex")
: receiverPrivateKey;
if (!secp256k1.privateKeyVerify(new Uint8Array(privKeyBuffer))) {
throw new Error("Invalid private key");
}
// Convert hex strings back to buffers
const ephemeralPubKey = Buffer.from(
encryptedMessage.ephemeralPublicKey,
"hex"
);
const salt = Buffer.from(encryptedMessage.salt, "hex");
const iv = Buffer.from(encryptedMessage.iv, "hex");
const encrypted = Buffer.from(encryptedMessage.encrypted, "hex");
const receivedMac = Buffer.from(encryptedMessage.mac, "hex");
// Verify ephemeral public key
if (!secp256k1.publicKeyVerify(new Uint8Array(ephemeralPubKey))) {
throw new Error("Invalid ephemeral public key");
}
// Derive shared secret using ECDH
const sharedSecret = deriveSharedSecret(privKeyBuffer, ephemeralPubKey);
// Derive encryption and MAC keys using HKDF
const derivedKeys = hkdf(sharedSecret, salt, "ECIES-encryption", 64);
const encryptionKey = derivedKeys.slice(0, 32);
const macKey = derivedKeys.slice(32, 64);
// Verify HMAC
const dataToAuth = Buffer.concat([ephemeralPubKey, salt, iv, encrypted]);
const computedMac = crypto
.createHmac("sha256", macKey)
.update(dataToAuth)
.digest();
if (!crypto.timingSafeEqual(receivedMac, computedMac)) {
throw new Error(
"MAC verification failed - message may have been tampered with"
);
}
// Decrypt message using AES-256-CBC
const decipher = crypto.createDecipheriv("aes-256-cbc", encryptionKey, iv);
let decrypted = decipher.update(encrypted);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted; // Return as Buffer to preserve binary data
}