1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP/JavaScriptで相互に動作する暗号復号関数

Posted at

概要

任意のパスワードと暗号化したいテキストのみで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ライブラリを使用します。

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);
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?