以下のサイトを参考にさせていただき、フォームから取得したテキストを暗号化してデータベースに保管し、取り出して復号化しようとしました。
[PHP]重要な文字列を暗号化して保管し、利用するときは復元する方法(OpenSSL使用)
まず、テキストを暗号化して登録します。
lang
1 //$passPhraseが入っているファイルを読み込み 2 require_once('../../common/openssl.php'); 3 4 //データベースに接続 5 require_once '../../common/db_config.php'; 6 $dsn="mysql:dbname=$dbname;host=$host;charset=utf8;"; 7 $dbh=new PDO($dsn,$user,$password); 8 $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); 9 $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 10 11 //暗号化 12 $passPhrase='$passPhrase'; 13 $method='AES-256-CBC'; 14 $iv_size=openssl_cipher_iv_length($method); 15 $iv=openssl_random_pseudo_bytes($iv_size); 16 $options=OPENSSL_RAW_DATA; 17 $text1=openssl_encrypt($text1,$method,$passPhrase,$options,$iv); 18 $text1=base64_encode($text1); 19 $text2=openssl_encrypt($text2,$method,$passPhrase,$options,$iv); 20 $text2=base64_encode($text2); 21 $text3=openssl_encrypt($text3,$method,$passPhrase,$options,$iv); 22 $text3=base64_encode($text3); 23 $base64_iv=base64_encode($iv); 24 25 //データベースに挿入 26 $sql='INSERT INTO table1(text1,text2,text3,iv) VALUES(?,?,?,?)'; 27 $stmt=$dbh->prepare($sql); 28 $stmt->bindParam(1,$text1,PDO::PARAM_STR); 29 $stmt->bindParam(2,$text2,PDO::PARAM_STR); 30 $stmt->bindParam(3,$text3,PDO::PARAM_STR); 31 $stmt->bindParam(4,$base64_iv,PDO::PARAM_STR); 32 $stmt->execute();
次に、別のファイルで、データベースに保存したテキストを取り出し、復号化しようとしました。
lang
1 //$passPhraseが入っているファイルを読み込み 2 require_once('../../common/openssl.php'); 3 4 //データベースに接続 5 require_once '../../common/db_config.php'; 6 $dsn="mysql:dbname=$dbname;host=$host;charset=utf8;"; 7 $dbh=new PDO($dsn,$user,$password); 8 $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); 9 $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 10 $sql=' 11 SELECT 12 table1.text1, 13 table1.text2, 14 table1.text3, 15 table1.iv, 16 FROM 17 table1 18 '; 19 $stmt=$dbh->prepare($sql); 20 $stmt->execute(); 21 $dbh=null; 22 23 while(true){ 24 $result=$stmt->fetch(PDO::FETCH_ASSOC); 25 if($result===false){ 26 break; 27 } 28 //復号化 29 $result['iv']=base64_decode($result['iv']); 30 $result['text1']=base64_decode($result['text1']); 31 $result['text2']=base64_decode($result['text2']); 32 $result['text3']=base64_decode($result['text3']); 33 $passPhrase=$passPhrase; 34 $method='AES-256-CBC'; 35 $options=OPENSSL_RAW_DATA; 36 $result['text1']=openssl_decrypt($result['text1'],$method,$passPhrase,$options,$result['iv']); 37 $result['text2']=openssl_decrypt($result['text2'],$method,$passPhrase,$options,$result['iv']); 38 $result['text3']=openssl_decrypt($result['text3'],$method,$passPhrase,$options,$result['iv']); 39 40var_dump($result); 41exit; 42
この段階で出力されるのが、
["text1"]=> bool(false) ["text2"]=> bool(false) ["text3"]=> bool(false) ["iv"]=> string(16) "l=!�;��-��Y�䈕"
という感じで復号化したい箇所がfalseになってしまいます。
わかりにくい説明で恐縮ですが、よろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/08 00:54
2018/09/08 02:13
2018/09/08 04:58
2018/09/08 05:29
2018/09/08 06:13