Source: util/crypt.js

/*
 * Copyright (c) 2020 Capgemini Group, Commissariat à l'énergie atomique et aux énergies alternatives,
 *                    OW2, Sysgo AG, Technikon, Tree Technology, Universitat Politècnica de València.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const crypto = require('crypto');

class Crypt
{
	/** constructor
	 * 
	 * @param {string} secret - secret (should be at least 32 characters)
	 */
	constructor(secret)
	{
		this.algorithm = 'aes-256-ctr';
		this.iv = crypto.randomBytes(16);
		this.secret = secret.slice(0, 2 * this.iv.length);
	}

	/** Encrypt a text
	 * 
	 * @param {string} text - a text
	 * @return {string} the encrypted text
	 */
	encrypt(text)
	{
		const cipher = crypto.createCipheriv(this.algorithm, this.secret, this.iv);

		const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);

		return this.iv.toString('hex') + encrypted.toString('hex');
	};

	/** Decrypt a text
	 * 
	 * @param {string} encrypted - an encrypted text
	 * @return {string} the text
	 */
	decrypt(encrypted)
	{
		const decipher = crypto.createDecipheriv(this.algorithm, this.secret, Buffer.from(encrypted.slice(0, 2 * this.iv.length), 'hex'));

		const decrypted = Buffer.concat([decipher.update(Buffer.from(encrypted.slice(2 * this.iv.length), 'hex')), decipher.final()]);

		return decrypted.toString();
	};
}

module.exports = Crypt;