Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Make crypto key check work in different node versions #31

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

pawanpaudel93
Copy link
Contributor

@pawanpaudel93 pawanpaudel93 commented Apr 24, 2024

Summary

This PR makes aesKey instanceof crypto.webcrypto.CryptoKey work on different node versions. For example, crypto.webcrypto.CryptoKey is undefined on node v20+.

Note

  • I am just fixing the instanceof issue on node v20+.
  • But we could also remove the isCryptoKey as aesKey is an ArrayBuffer so isCryptoKey(aesKey) is always false.

How To Test

  • [Without Fix] Run this in different node versions. (For eg: You could test in node 18 (Success) and 20 (Fails))
import crypto from 'crypto';

function isCryptoKey(obj) {
    return obj instanceof crypto.webcrypto.CryptoKey;
}

async function generateKey() {
    return await crypto.webcrypto.subtle.generateKey(
        {
            name: 'AES-GCM',
            length: 256,
        },
        true,
        ['encrypt', 'decrypt']
    );
}

async function checkIfCryptoKey() {
    const key = await generateKey();
    console.log(isCryptoKey(key));
}

checkIfCryptoKey().catch(console.error);
  • [With Fix] Run this in different node versions. (For eg: You could test in node 18 (Success) and 20 (Success))
import crypto from 'crypto';

function isCryptoKey(obj) {
    try {
        return obj instanceof CryptoKey;
    } catch (e) {
        return obj instanceof crypto.webcrypto.CryptoKey;
    }
}

async function generateKey() {
    return await crypto.webcrypto.subtle.generateKey(
        {
            name: 'AES-GCM',
            length: 256,
        },
        true,
        ['encrypt', 'decrypt']
    );
}

async function checkIfCryptoKey() {
    const key = await generateKey();
    console.log(isCryptoKey(key));
}

checkIfCryptoKey().catch(console.error);

@pawanpaudel93 pawanpaudel93 requested a review from 7i7o April 24, 2024 17:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant