feat: fix iv

This commit is contained in:
Nevo David 2025-10-17 01:34:05 +07:00
parent ac13f44bbf
commit 0cdc0b850a
3 changed files with 14 additions and 19 deletions

View File

@ -10,7 +10,7 @@ import { CreateAgencyDto } from '@gitroom/nestjs-libraries/dtos/agencies/create.
export class AgenciesController {
constructor(private _agenciesService: AgenciesService) {}
@Get('/')
async getAgencyByUser(@GetUserFromRequest() user: User) {
async getAgencyByUsers(@GetUserFromRequest() user: User) {
return (await this._agenciesService.getAgencyByUser(user)) || {};
}

View File

@ -14,7 +14,7 @@ export class PostsController {
@EventPattern('post', Transport.REDIS)
async post(data: { id: string }) {
console.log('process', data);
console.log('processing', data);
try {
return await this._postsService.post(data.id);
} catch (err) {

View File

@ -1,42 +1,37 @@
import { sign, verify } from 'jsonwebtoken';
import { hashSync, compareSync } from 'bcrypt';
import crypto from 'crypto';
// @ts-ignore
import EVP_BytesToKey from 'evp_bytestokey';
const algorithm = 'aes-256-cbc';
const { keyLength, ivLength } = crypto.getCipherInfo(algorithm);
function deriveLegacyKeyIv(secret) {
const pass = Buffer.isBuffer(secret)
? secret
: Buffer.from(secret ?? '', 'utf8');
// EVP_BytesToKey(password, salt, keyLen, ivLen) — lengths are BYTES
const { key, iv } = EVP_BytesToKey(pass, null, keyLength, ivLength); // MD5, 1 iter, no salt (legacy)
function deriveLegacyKeyIv(secret: string) {
const { keyLength, ivLength } = crypto.getCipherInfo(algorithm); // 32, 16
const pass = Buffer.isBuffer(secret) ? secret : Buffer.from(secret ?? '', 'utf8');
// evp_bytestokey: key length in **bits**, IV length in **bytes**
const { key, iv } = EVP_BytesToKey(pass, null, keyLength * 8, ivLength, 'md5');
if (key.length !== keyLength || iv.length !== ivLength) {
throw new Error(`Derived wrong sizes (key=${key.length}, iv=${iv.length})`);
}
return { key, iv };
}
export function decrypt_legacy_using_IV(hexCiphertext) {
export function decrypt_legacy_using_IV(hexCiphertext: string) {
const { key, iv } = deriveLegacyKeyIv(process.env.JWT_SECRET);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
const out = Buffer.concat([
decipher.update(hexCiphertext, 'hex'),
decipher.final(),
]);
const out = Buffer.concat([decipher.update(hexCiphertext, 'hex'), decipher.final()]);
return out.toString('utf8');
}
export function encrypt_legacy_using_IV(utf8Plaintext) {
export function encrypt_legacy_using_IV(utf8Plaintext: string) {
const { key, iv } = deriveLegacyKeyIv(process.env.JWT_SECRET);
const cipher = crypto.createCipheriv(algorithm, key, iv);
const out = Buffer.concat([
cipher.update(utf8Plaintext, 'utf8'),
cipher.final(),
]);
const out = Buffer.concat([cipher.update(utf8Plaintext, 'utf8'), cipher.final()]);
return out.toString('hex');
}
export class AuthService {
static hashPassword(password: string) {
return hashSync(password, 10);