Created
November 30, 2023 18:11
-
-
Save Nodonisko/11a8e27360bde9a8c489c840c14ec618 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// There is incomparability in results between nodejs and window SubtleCrypto api. | |
// window.crypto.subtle.importKey (CryptoKey) cannot be used by `crypto-browserify`.Verify | |
// The only common format of publicKey is PEM. | |
const verifySignature = async (rawKey: Buffer, data: Uint8Array, signature: Uint8Array) => { | |
const signer = crypto.createVerify('sha256'); | |
signer.update(Buffer.from(data)); | |
// use native SubtleCrypto api. | |
// Unfortunately `crypto-browserify`.subtle polyfill is missing so needs to be referenced directly from window object (if exists) | |
// https://github.com/browserify/crypto-browserify/issues/221 | |
const SubtleCrypto = typeof window !== 'undefined' ? window.crypto.subtle : crypto.subtle; | |
if (!SubtleCrypto) { | |
throw new Error('SubtleCrypto not supported'); | |
} | |
// get ECDSA P-256 (secp256r1) key from RAW key | |
const ecPubKey = await SubtleCrypto.importKey( | |
'raw', | |
rawKey, | |
{ name: 'ECDSA', namedCurve: 'P-256' }, | |
true, | |
['verify'], | |
); | |
// export ECDSA key as spki | |
const spkiPubKey = await SubtleCrypto.exportKey('spki', ecPubKey); | |
// create PEM from spki | |
const key = `-----BEGIN PUBLIC KEY-----\n${Buffer.from(spkiPubKey).toString( | |
'base64', | |
)}\n-----END PUBLIC KEY-----`; | |
// verify using PEM key | |
return signer.verify({ key }, Buffer.from(signature)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment