38 lines
1.7 KiB
JavaScript
38 lines
1.7 KiB
JavaScript
const { subtle } = require('node:crypto').webcrypto;
|
|
const authentication = require('../src/authentication');
|
|
|
|
describe('authentication module', () => {
|
|
describe('verifySignature', () => {
|
|
it('should return the public key if the signature is verified successfully', async () => {
|
|
const { publicKey, privateKey } = await crypto.subtle.generateKey(
|
|
{
|
|
name: "Ed25519",
|
|
},
|
|
true,
|
|
["sign", "verify"],
|
|
);
|
|
const exportedPubkey = await crypto.subtle.exportKey("spki", publicKey);
|
|
let exportedAsString = String.fromCharCode.apply(null, new Uint8Array(exportedPubkey));
|
|
let exportedAsBase64 = Buffer.from(exportedAsString, 'binary').toString('base64');
|
|
let pemKey = `-----BEGIN PUBLIC KEY-----\n${exportedAsBase64}\n-----END PUBLIC KEY-----`;
|
|
const publicKeys = [pemKey,];
|
|
const msg = 'test message';
|
|
const encoder = new TextEncoder();
|
|
const encodedData = encoder.encode(msg);
|
|
const signature = await crypto.subtle.sign(
|
|
{
|
|
name: "Ed25519",
|
|
},
|
|
privateKey,
|
|
encodedData,
|
|
);
|
|
const result = await authentication.verifySignature(encodedData, signature, publicKeys);
|
|
expect(result).toBe(pemKey);
|
|
|
|
let fakeKey = `-----BEGIN PUBLIC KEY-----MCowBQYDK2VwAyEAmrBLT6lyiFh/eUticsIFNY6AkjXuQPqj0Qvb99pCJJk=-----END PUBLIC KEY-----`
|
|
const result2 = await authentication.verifySignature(encodedData, signature, [fakeKey,]);
|
|
expect(result2).toBe(null);
|
|
});
|
|
});
|
|
});
|