我对此密码学课程有一些问题。我是PHP的新手,我确信这是一个小问题,但有人能指出我正确的方向吗?该代码目前根本不起作用。
这是代码
Cryptography.php
class Cryptography
{
# the key should be random binary, use scrypt, bcrypt or PBKDF2 to
# convert a string into a key
# key is specified using hexadecimal
# use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
private static $key = pack('H*', "I-AINT-SHOWING-YOU-MY-KEY-LOL");
private static $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
public static function encrypt($plaintext)
{
# --- ENCRYPTION ---
# create a random IV to use with CBC encoding
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
# prepend the IV for it to be available for decryption
$ciphertext = $iv . $ciphertext;
# encode the resulting cipher text so it can be represented by a string
return base64_encode($ciphertext);
}
public static function decrypt($ciphertext_base64)
{
# --- DECRYPTION ---
$ciphertext_dec = base64_decode($ciphertext_base64);
# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
# may remove 00h valued characters from end of plain text
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
}
}
test.php的
require_once('Cryptography.php');
$text = 'This is the string I am going to encrypt' . "\n\n";
echo $text;
$encrypted_text = Cryptography::encrypt($text);
echo "{$encrypted_text}\n\n";
$decrypted_text = Cryptography::decrypt($encrypted_text);
echo "{$decrypted_text}\n\n";
答案 0 :(得分:0)
static $ key不能是另一个函数的输出。它必须是文字的。您可以将$key
更改为某个功能,例如create_key()
并返回pack()
输出。必须将所有$key
更改为self::create_key()
。同样关注$iv_size
,它也需要转换为self::get_iv_size()
。
private static function create_key(){
return pack('H*', "I-AINT-SHOWING-YOU-MY-KEY-LOL");
}
private static function get_iv_size(){
return mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
}