2021-02-08 11:32:58 +01:00
|
|
|
import { Component, OnInit } from '@angular/core';
|
2021-02-09 18:26:13 +01:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
|
|
const crypto = require('crypto');
|
|
|
|
// documentation:
|
|
|
|
// https://medium.com/@spatocode/symmetric-encryption-in-javascript-bcb5fd14c273
|
|
|
|
// https://nodejs.org/api/crypto.html
|
2021-02-08 11:32:58 +01:00
|
|
|
@Component({
|
|
|
|
selector: 'app-ciphering',
|
|
|
|
templateUrl: './ciphering.component.html',
|
|
|
|
styleUrls: ['./ciphering.component.scss'],
|
|
|
|
})
|
|
|
|
export class CipheringComponent implements OnInit {
|
2021-02-09 18:26:13 +01:00
|
|
|
public plainText = 'le texte à chiffrer, coucou !';
|
2021-02-08 11:32:58 +01:00
|
|
|
public cipheredText = '';
|
2021-02-09 18:26:13 +01:00
|
|
|
algorithm = 'aes-192-cbc';
|
|
|
|
public salt = crypto.randomBytes(16);
|
|
|
|
public initial_vector = crypto.randomBytes(16);
|
|
|
|
public key = '';
|
2021-02-08 11:32:58 +01:00
|
|
|
public otherCipheredText: any;
|
|
|
|
|
|
|
|
constructor() {}
|
|
|
|
|
|
|
|
ngOnInit(): void {
|
|
|
|
this.encrypt(this.plainText);
|
|
|
|
}
|
|
|
|
|
|
|
|
encrypt(someText) {
|
2021-02-09 18:26:13 +01:00
|
|
|
this.key = crypto.scryptSync(someText, 'salt', 24);
|
|
|
|
this.initial_vector = crypto.randomBytes(16);
|
|
|
|
|
|
|
|
const cipher = crypto.createCipheriv(this.algorithm, this.key, this.initial_vector);
|
|
|
|
|
|
|
|
cipher.on('readable', () => {
|
|
|
|
this.cipheredText = cipher.read().toString('hex');
|
|
|
|
console.log(cipher.read().toString('hex'));
|
|
|
|
});
|
|
|
|
|
|
|
|
let output = '';
|
|
|
|
|
2021-02-08 11:32:58 +01:00
|
|
|
this.cipheredText = someText;
|
|
|
|
// outputs encrypted hex
|
|
|
|
console.log(this.cipheredText);
|
|
|
|
}
|
2021-02-09 18:26:13 +01:00
|
|
|
|
|
|
|
decrypt(sometext) {
|
|
|
|
const decipher = crypto.createDecipheriv(this.algorithm, this.key, this.initial_vector);
|
|
|
|
|
|
|
|
decipher.on('readable', () => {
|
|
|
|
this.otherCipheredText = decipher.read().toString('utf8');
|
|
|
|
|
|
|
|
console.log('otherCipheredText decrypt', this.otherCipheredText);
|
|
|
|
});
|
|
|
|
|
|
|
|
decipher.write(sometext, 'hex');
|
|
|
|
decipher.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
convertTextToInt(someText) {
|
|
|
|
let output = '';
|
|
|
|
|
|
|
|
for (let i = 0; i < someText.length; i++) {
|
|
|
|
output += someText[i].charCodeAt(0);
|
|
|
|
}
|
|
|
|
return output;
|
|
|
|
}
|
2021-02-08 11:32:58 +01:00
|
|
|
}
|