「Php/可逆暗号」の版間の差分
提供: 初心者エンジニアの簡易メモ
| (同じ利用者による、間の1版が非表示) | |||
| 行3: | 行3: | ||
openssl拡張は、デフォで入ってるのでインストール不要。 | openssl拡張は、デフォで入ってるのでインストール不要。 | ||
| − | == | + | ===サンプル=== |
AESCrypt.php | AESCrypt.php | ||
<pre> | <pre> | ||
| 行71: | 行71: | ||
Pear::Crypt_Blowfishを使う | Pear::Crypt_Blowfishを使う | ||
| − | === | + | ===インストール=== |
pear install Crypt_Blowfish | pear install Crypt_Blowfish | ||
| − | === | + | ===サンプル=== |
<?php | <?php | ||
require_once 'Crypt/Blowfish.php'; | require_once 'Crypt/Blowfish.php'; | ||
2026年4月24日 (金) 03:49時点における最新版
AES
openssl拡張は、デフォで入ってるのでインストール不要。
サンプル
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を使う
インストール
pear install Crypt_Blowfish
サンプル
<?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";
