LoginSignup
1
2

More than 3 years have passed since last update.

PHPで暗号化した情報をGoogle Colab(Python)で復号する

Posted at

Google Colabでインターネット上にある情報にアクセスできるのは便利だ。個人情報や機密情報をインターネット上に置くのはもってのほかだが、インターネット上に公開して問題ないが第三者に利用されたくないので暗号化しておくといった場合があるかもしれない。(というか、このあたりは自己責任で)

まず、PHPで暗号化して出力する方から。AES256(CBCモード)で暗号化する。

$message = "Hello"
$plaintext = sprintf("%s %s",date("Y-m-d"),$message);
$cipher = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$key = "12345678901234567890123456789012";
$ciphertext_raw = openssl_encrypt($plaintext,$cipher,$key,$options=OPENSSL_RAW_DATA,$iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$ciphertext_raw );
print($ciphertext);

1234...で書いているAESの鍵は

openssl rand -base64 1000 | dd of=sample.key bs=32 count=1

などで生成したものを使う。

次にGoogle Colab。事前にpycryptoをインストールしておく。

pip install pycrypto

example.comのログをpandasで格納し、1行ごとに復号する。

import base64
from Crypto import Random
from Crypto.Cipher import AES
import pandas as pd

df = pd.read_csv("https://example.com/test.php",header=None)

key = "12345678901234567890123456789012"

for index,data in df.iterrows():
  c = base64.b64decode(data[0])
  iv = c[:AES.block_size]
  cipher = AES.new(key, AES.MODE_CBC, iv)
  s = cipher.decrypt(c[AES.block_size:])
  s = s[:-ord(s[len(s)-1:])]
  print(s)

iv(initial vector)の扱いが各言語のリファレンスごとに微妙に違って苦労したが、とりあえずPHPで出力したAES暗号をGoogle Colabで復号できるようになった。

繰り返すが、暗号化すれば公開していいというものではないので、扱いは自己責任で。

1
2
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
2