概要
任意のパスワードと暗号化したいテキストのみでPHPとJavaScriptで相互に暗号←→復号できる関数を示します。
PHP
encrypt.php
function encrypt(string $plaintext, string $passphrase) :string
{
$cipher = "aes-256-cbc";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$key = hash('sha256', $passphrase, true);
$encrypted = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv . $encrypted);
return $encrypted;
}
decrypt.php
function resvDecrypt(string $encryptedText, string $passphrase) :string
{
$cipher = "aes-256-cbc";
$key = hash('sha256', $passphrase, true);
$ivLength = openssl_cipher_iv_length($cipher);
$data = base64_decode($encryptedText);
$iv = substr($data, 0, $ivLength);
$encrypted = substr($data, $ivLength);
$decrypted = openssl_decrypt($encrypted, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
JavaScript
JavaScriptはcrypto-jsライブラリを使用します。
encrypt.js
import CryptoJS from 'crypto-js';
function encrypt(message, passphrase) {
const key = CryptoJS.SHA256(passphrase);
const iv = CryptoJS.lib.WordArray.random(16);
const encrypted = CryptoJS.AES.encrypt(message, key, {
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
const encryptedMessage = iv.concat(encrypted.ciphertext).toString(CryptoJS.enc.Base64);
return encryptedMessage;
}
decrypt.js
import CryptoJS from 'crypto-js';
function decrypt(encryptedText, passphrase) {
const encryptedBytes = CryptoJS.enc.Base64.parse(encryptedText);
const iv = CryptoJS.lib.WordArray.create(encryptedBytes.words.slice(0, 4));
const ciphertext = CryptoJS.lib.WordArray.create(encryptedBytes.words.slice(4));
const key = CryptoJS.SHA256(passphrase);
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext },
key,
{
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}
);
return decrypted.toString(CryptoJS.enc.Utf8);
}