0

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])
}

Topaco
  • 40,594
  • 4
  • 35
  • 62
alal
  • 1
  • 1
    The result of your encryption is the concatenation of salt, nonce, ciphertext and tag (in that order) and thus contains all the data needed for decryption. During decryption the parts are to be separated on the basis of the known lengths of salt, nonce and tag. With the salt the key is derived with PBKDF2 (analogous to encryption using the same PBKDF2 parameters). With the derived key, as well as nonce and tag, the ciphertext is decrypted with AES/GCM. – Topaco May 21 '23 at 07:10

0 Answers0