-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
61 lines (48 loc) · 2.01 KB
/
script.js
File metadata and controls
61 lines (48 loc) · 2.01 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
// Import necessary libraries
const EC = require('elliptic').ec;
const crypto = require('crypto');
// 1. Create elliptic curve object (secp256k1, same as Bitcoin and Ethereum)
const ec = new EC('secp256k1');
// 1. Generate Private Key
const keyPair = ec.genKeyPair();
const privateKey = keyPair.getPrivate('hex');
console.log("Private Key:", privateKey);
// 2. Derive Public Key
const publicKey = keyPair.getPublic('hex');
console.log("Public Key:", publicKey);
// 3. Generate Address from Public Key (Using SHA-256 and then RIPEMD160 like in BTC)
const publicKeyBuffer = Buffer.from(publicKey, 'hex');
const sha256Hash = crypto.createHash('sha256').update(publicKeyBuffer).digest();
const ripemd160Hash = crypto.createHash('ripemd160').update(sha256Hash).digest('hex');
const address = ripemd160Hash;
console.log("Generated Address:", address);
// 4. Create a message
function createNameMessage(firstName, lastName) {
// Regex to match only letters (uppercase and lowercase)
const letterOnlyRegex = /^[A-Za-z]+$/;
if (!letterOnlyRegex.test(firstName)) {
throw new Error("First name must contain only letters.");
}
if (!letterOnlyRegex.test(lastName)) {
throw new Error("Last name must contain only letters.");
}
const message = `My name is ${firstName} ${lastName}`;
console.log("Original Message:", message);
}
// Example usage
try {
createNameMessage("Mohammed", "Mshelbwala");
} catch (error) {
console.error("Error:", error.message);
}
// 5. Hash the message
const messageHash = crypto.createHash('sha256').update(message).digest('hex');
console.log("Hashed Message:", messageHash);
// 6. Create Digital Signature using the private key
const signature = keyPair.sign(messageHash);
const signatureHex = signature.toDER('hex');
console.log("Digital Signature:", signatureHex);
// 7. Verify Signature (Receiver side)
const publicKeyFromSender = ec.keyFromPublic(publicKey, 'hex');
const isVerified = publicKeyFromSender.verify(messageHash, signatureHex);
console.log("Is the signature valid?", isVerified);