【发布时间】:2015-03-06 07:48:07
【问题描述】:
我在这个密码学课程方面遇到了一些问题。我是 PHP 新手,我敢肯定这是一个小的语法问题,但谁能指出我正确的方向?该代码目前根本不起作用。
这里是代码
密码学.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";
【问题讨论】:
-
'它不起作用' 不是一个充分的问题描述。
-
这是我收到的错误消息之一“解析错误:语法错误,意外 '(', 期待 ',' 或 ';' in path\Cryptography.php on line 10”其中第 10 行是声明密钥的行
-
在函数定义中,您需要将
$iv_size和$key变量更改为self::$iv_size和self::$key,因为它们属于同一类 - 您可能会收到未定义的通知现在。 -
谢谢@n-dru,我已经按照你说的做了。仍然会出现关于第 10 行的相同错误消息。
-
静态变量只能用文字或常量初始化。 Reference
标签: php static cryptography