@qnx/crypto
provides utility functions to generate and decrypt JSON Web Signatures (JWS) and JSON Web Encryption (JWE) using the jose cryptography library for secure data transmission.
Use the package manager npm to install @qnx/crypto.
npm install @qnx/crypto
yarn add @qnx/crypto
pnpm install @qnx/crypto
@qnx/crypto is using JOSE.
npm install jose
- jwtSign
- jwtVerify
- jweEncrypt
- jweDecrypt
jwtSign: Signs and returns the JWT.
import { jwtSign, toSymmetricSecret } from '@qnx/crypto'
const dataVal = {
foo: 'bar'
}
const jwt = await jwtSign({ data: dataVal }, toSymmetricSecret('SECRET_STRING'), {
alg: 'HS256'
})
jwtVerify: Verifies the JWT format, signature, and claims set.
import { jwtVerify, toSymmetricSecret } from '@qnx/crypto'
const { payload } = await jwtVerify(jwt, toSymmetricSecret('SECRET_STRING'))
jweEncrypt: Encrypts a value of the JWE string.
import { jweEncrypt, toPKCS8Secret } from '@qnx/crypto'
const secret = await toPKCS8Secret(process.env['ENCRYPTION_SECRET_JWE'], 'ECDH-ES+A128KW')
const dataVal = 'this is message.'
const jwe = await jweEncrypt(dataVal, secret)
jweDecrypt: Decrypts a JWE.
import { jweDecrypt, toPKCS8Secret } from '@qnx/crypto'
const secret = await toPKCS8Secret(process.env['ENCRYPTION_SECRET_JWE'], 'ECDH-ES+A128KW')
const jwe = 'JWE_TOKEN'
const { plaintext } = await jweDecrypt(jwe, secret)
Ensure you have the necessary environment variables set:
ENCRYPTION_SECRET_JWT: The secret key used for JWT signing
ENCRYPTION_SECRET_JWE: The secret key used for JWT encryption
generateAuthToken: Creates a JWE for authentication purposes.
import { generateAuthToken } from '@qnx/crypto'
const subject = 'userId'
const { token, dbToken } = await generateToken(subject)
// token: The encrypted JWT token
// dbToken: The unique identifier associated with the token
decryptToken: Decrypts a JWE token and verifies its authenticity.
import { decryptAuthToken } from '@qnx/crypto'
const encryptedToken = '...' // Replace with the encrypted token
try {
const decryptedPayload = await decryptToken(encryptedToken)
// decryptedPayload: The decoded payload from the token
} catch (error) {
// Handle decryption errors
console.error('Token decryption failed:', error)
}
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.
MIT License © 2023-PRESENT Yatendra Kushwaha