Da ich für ein internes Project eine AES Ver-/Entschlüsselung mit Passwort in PHP implementieren musste und der die Ver-/Entschlüsselung des Ganzen auch unter JavaScript (NodeJS) funktionieren sollte, dachte ich mir das ich euch die beiden Klassen (PHP+JavaScript) mal hier zur Verfügung stelle, falls jemand etwas ähnliches sucht und braucht.
Sollte jemand Verbesserungsvorschläge haben, bin ich dem gegenüber natürlich offen
Voraussetzungen:
PHP 7.x + OpenSSL
NodeJS > 8.x + "crypto" Modul
PHP Implementation
JavaScript/NodeJS implementation
Nachtrag:
Sorry falsches Forum, kann von den Mods mal bitte einer diesen Beitrag in die Scriptbörse verschieben? Danke
Sollte jemand Verbesserungsvorschläge haben, bin ich dem gegenüber natürlich offen
Voraussetzungen:
PHP 7.x + OpenSSL
NodeJS > 8.x + "crypto" Modul
PHP Implementation
PHP-Code:
<?php
class Cipher
{
private static $_AESMethod = 'aes-256-cbc';
/**
* Encrypt $plain with $password
*
* @param string $plain
* @param string $password
* @return string
*/
public static function encrypt(string $plain, string $password) : string
{
$iv_size = openssl_cipher_iv_length(self::$_AESMethod);
$iv = openssl_random_pseudo_bytes($iv_size);
$ciphertext = openssl_encrypt($plain, self::$_AESMethod, $password, OPENSSL_RAW_DATA, $iv);
$ciphertext_hex = bin2hex($ciphertext);
$iv_hex = bin2hex($iv);
return "$iv_hex:$ciphertext_hex";
}
/**
* Decrypt $encrypted with $password
*
* @param string $encrypted
* @param string $password
* @return string
*/
public static function decrypt(string $encrypted, string $password) : string
{
$data = explode(':', $encrypted);
$iv = hex2bin($data[0]);
$cipher = hex2bin($data[1]);
return openssl_decrypt($cipher, self::$_AESMethod, $password, OPENSSL_RAW_DATA, $iv);
}
}
PHP-Code:
const Crypto = require('crypto');
const IV_LENGTH = 16;
const AES_METHOD = 'aes-256-cbc';
module.exports = class Cipher {
/**
* @constructor
*/
constructor() { }
/**
* Encrypt "plain" with "password".
*
* @param {String} plain
* @param {String} password
* @returns {String}
*/
encrypt(plain, password)
{
let iv = Crypto.randomBytes(IV_LENGTH);
let cipher = Crypto.createCipheriv(AES_METHOD, new Buffer.from(password), iv);
let encrypted = cipher.update(plain);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
/**
* Decrypt "encrypted" with "password"
*
* @param {String} encrypted
* @param {String} password
* @return {String}
*/
decrypt(encrypted, password)
{
let textParts = encrypted.split(':');
let iv = new Buffer.from(textParts.shift(), 'hex');
let encryptedText = new Buffer.from(textParts.join(':'), 'hex');
let decipher = Crypto.createDecipheriv(AES_METHOD, new Buffer.from(password), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
}
Nachtrag:
Sorry falsches Forum, kann von den Mods mal bitte einer diesen Beitrag in die Scriptbörse verschieben? Danke
Kommentar