PHP加密类问题


PHP Cryptography Class Issues

关于这个Cryptography类,我遇到了一些问题。我是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);
    } 
}

测试.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";

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);
}