facebook twitter hatena line email

Php/可逆暗号

提供: 初心者エンジニアの簡易メモ
2026年4月24日 (金) 00:59時点におけるAdmin (トーク | 投稿記録)による版

移動: 案内検索

AES

smaple

AESCrypt.php

class AESCrypt
{
    private string $key;

    public function __construct(string $key)
    {
        // 32バイト(256bit)に正規化
        $this->key = hash('sha256', $key, true);
    }

    public function encrypt(string $plainText): string
    {
        $iv = random_bytes(12); // GCMは12バイト推奨
        $tag = '';

        $cipherText = openssl_encrypt(
            $plainText,
            'aes-256-gcm',
            $this->key,
            OPENSSL_RAW_DATA,
            $iv,
            $tag
        );

        // iv + tag + ciphertext をまとめてbase64
        return base64_encode($iv . $tag . $cipherText);
    }

    public function decrypt(string $encrypted): string|false
    {
        $data = base64_decode($encrypted);

        $iv  = substr($data, 0, 12);
        $tag = substr($data, 12, 16);
        $cipherText = substr($data, 28);

        return openssl_decrypt(
            $cipherText,
            'aes-256-gcm',
            $this->key,
            OPENSSL_RAW_DATA,
            $iv,
            $tag
        );
    }
}

呼び出し

$key = 'your-secret-key';
$crypto = new AESCrypt($key);

// 暗号化
$encrypted = $crypto->encrypt('hello world');

// 復号
$decrypted = $crypto->decrypt($encrypted);

echo $encrypted . PHP_EOL;
echo $decrypted . PHP_EOL;

Blowfish

Pear::Crypt_Blowfishを使う

install

pear install Crypt_Blowfish

sample

<?php
require_once 'Crypt/Blowfish.php';

$key = "testtest";
$text = "1234567890";

$blowfish = new Crypt_Blowfish($key);
$encrypt = base64_encode($blowfish->encrypt($text));
$decrypt = rtrim($blowfish->decrypt(base64_decode($encrypt)), "\0");

print $encrypt;
print "\n";
print $decrypt;
print "\n";