Passed
Pull Request — master (#90)
by Mathieu
01:40
created

FileEncryptionAdapter.decrypt   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
1
import * as crypto from 'crypto';
2
import {Injectable} from '@nestjs/common';
3
import {ConfigService} from '@nestjs/config';
4
import {IFileEncryption} from 'src/Application/IFileEncryption';
5
6
@Injectable()
7
export class FileEncryptionAdapter implements IFileEncryption {
8
  constructor(private readonly configService: ConfigService) {}
9
10
  public async encrypt(buffer: Buffer): Promise<Buffer> {
11
    const iv = crypto.randomBytes(16);
12
    const key = await this.getEncryptionKey();
13
    const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
14
15
    return Buffer.concat([iv, cipher.update(buffer), cipher.final()]);
16
  }
17
18
  public async decrypt(buffer: Buffer): Promise<Buffer> {
19
    const key = await this.getEncryptionKey();
20
    const iv = buffer.slice(0, 16);
21
    const decipher = crypto.createDecipheriv('aes-256-ctr', key, iv);
22
23
    return Buffer.concat([decipher.update(buffer.slice(16)), decipher.final()]);
24
  }
25
26
  private async getEncryptionKey(): Promise<string> {
27
    const key = await this.configService.get<string>('FILE_ENCRYPTION_KEY');
28
29
    return crypto
30
      .createHash('sha256')
31
      .update(key)
32
      .digest('base64')
33
      .substr(0, 32);
34
  }
35
}
36