-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-api-credential
executable file
·57 lines (48 loc) · 1.69 KB
/
generate-api-credential
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
#!/usr/bin/env node
const ethers = require('ethers');
const { Base64 } = require('js-base64');
async function generateKeyPairAndSignature(privateKeyInput) {
try {
// Create wallet from provided private key or generate new random wallet
const wallet = privateKeyInput
? new ethers.Wallet(privateKeyInput)
: ethers.Wallet.createRandom();
const publicAddress = wallet.address;
// Sign the public address using the private key
const signature = await wallet.signMessage(publicAddress);
// Base64 encode the signature before creating the auth string
const base64Signature = Base64.encode(
Buffer.from(signature.slice(2), 'hex'),
);
// Create the basic auth credential in the format expected by the middleware
const basicAuthString = `${publicAddress}:${base64Signature}`;
const basicAuthHeader = `basic ${Base64.encode(basicAuthString)}`;
return {
privateKey: wallet.privateKey,
publicAddress,
signature,
basicAuthHeader,
};
} catch (error) {
console.error('Error:', error.message);
throw error;
}
}
// Execute the function
(async () => {
// Get private key from command line argument if provided
const providedPrivateKey = process.argv[2];
const { privateKey, publicAddress, signature, basicAuthHeader } =
await generateKeyPairAndSignature(providedPrivateKey);
console.log('Authentication Details:');
console.log('Private Key:', privateKey);
console.log('Public Address:', publicAddress);
console.log('\nFor Basic Auth:');
console.log('Authorization Header:', basicAuthHeader);
console.log('\nFor Manual Construction:');
console.log('Username:', publicAddress);
console.log(
'Password:',
Base64.encode(Buffer.from(signature.slice(2), 'hex')),
);
})();