how to decrypt a message with crypto.pbkdf2

98 Views Asked by At

i cant find a way decrypt a message using crypto library

im using a service that encrypts messages using the following logic (its not my service, i cant change the encryption function), after a very long search i couldn't find a way to decrypt it, i found some previous items here, but none helped .

import * as crypto from "crypto"

const PBKDF2_SALT_SIZE = 16
const PBKDF2_ALGO_NAME = "sha256"
const PBKDF2_ITERATIONS = 1000
const ENCRYPT_ALGO_NAME = "aes-128-gcm"
const ENCRYPT_ALGO_NONCE_SIZE = 10
const ENCRYPT_ALGO_KEY_SIZE = 10

const pass = "abcd"

async function encrypt(plainText: string): Promise<string> {
    if (plainText?.length === 0) {
        return Promise.resolve("")
    }
    const salt = crypto.randomBytes(PBKDF2_SALT_SIZE)

    return await new Promise((resolve, reject) => {
        crypto.pbkdf2(
            pass,
            salt,
            PBKDF2_ITERATIONS,
            ENCRYPT_ALGO_KEY_SIZE,
            PBKDF2_ALGO_NAME,
            (err, derivedKey: Buffer) => {
                if (err) {
                    return reject(err)
                }
                const encrypted = encryptWithBuffKey(plainText, derivedKey)
                const res = Buffer.concat([salt, encrypted]).toString("base64")
                resolve(res)
            }
        )
    })
}
function encryptWithBuffKey(plainText: string, key: Buffer) {
    const nonce = crypto.randomBytes(ENCRYPT_ALGO_NONCE_SIZE)
    const cipher = crypto.createCipheriv(ENCRYPT_ALGO_NAME, key, nonce)
    const encrypted = Buffer.concat([cipher.update(plainText), cipher.final()])
    const tag = cipher.getAuthTag()

    return Buffer.concat([nonce, encrypted, tag])
}

0

There are 0 best solutions below