Dcrypt\Mcrypt::encrypt PHP Method

encrypt() public static method

Encrypt plaintext
public static encrypt ( string $plaintext, string $password, integer $cost, string $cipher = MCRYPT_RIJNDAEL_128, string $mode = MCRYPT_MODE_CBC, string $algo = 'sha256' ) : string
$plaintext string Plaintext string to encrypt
$password string Key used to encrypt data
$cost integer Number of HMAC iterations to perform on key
$cipher string Mcrypt cipher
$mode string Mcrypt mode
$algo string Hashing algorithm to use for internal operations
return string
    public static function encrypt($plaintext, $password, $cost = 0, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC, $algo = 'sha256')
    {
        // Pad the input string to a multiple of block size
        $padded = Pkcs7::pad($plaintext, \mcrypt_get_block_size($cipher, $mode));
        // Generate IV of appropriate size
        $iv = Random::bytes(\mcrypt_get_iv_size($cipher, $mode));
        // Derive key from password
        $key = self::key($password, $iv, $cost, $cipher, $mode, $algo);
        // Encrypt the plaintext
        $message = \mcrypt_encrypt($cipher, $key, $padded, $mode, $iv);
        // Create the cypher text prefix (iv + checksum)
        $prefix = $iv . self::checksum($message, $iv, $key, $cipher, $mode, $algo);
        // Return prefix + cyphertext
        return $prefix . $message;
    }

Usage Example

Beispiel #1
0
 public function testEngine()
 {
     // If PHP 7.1, skip this test
     if (self::mcryptDeprecated()) {
         $this->assertTrue(true);
         return;
     }
     $modes = self::mcryptModes();
     $ciphers = self::mcryptCiphers();
     foreach (hash_algos() as $algo) {
         $input = 'AAAAAAAA';
         $key = 'AAAAAAAA';
         $cost = 0;
         foreach ($modes as $mode) {
             foreach ($ciphers as $cipher) {
                 $encrypted = Mcrypt::encrypt($input, $key, $cost, $cipher, $mode, $algo);
                 $this->assertEquals($input, Mcrypt::decrypt($encrypted, $key, $cost, $cipher, $mode, $algo));
             }
         }
     }
 }