function __construct($cipher)
 {
     $this->cipher = $cipher;
     $this->key_size = mcrypt_module_get_algo_key_size($cipher);
     $this->block_size = mcrypt_module_get_algo_block_size($cipher);
     $this->iv = str_repeat("", mcrypt_get_iv_size($cipher, 'ncfb'));
 }
Exemple #2
0
    /**
     * Decrypt a text using Mcrypt
     *
     * @see http://maxime-ohayon.developpez.com/tutoriels/mcrypt
     * @param string $algorithm, ex : MCRYPT_3DES, MCRYPT_BLOWFISH, etc. see Mcrpyt doc
     * @param string $mode,      ex : MCRYPT_MODE_ECB, MCRYPT_MODE_NOFB, etc. see Mcrpyt doc
     * @param string $key        = your secret key or passphrase
     * @param string $encrypted  : your value to be decrypted
     */
    public static function decrypt($algorithm = MCRYPT_BLOWFISH, $mode = MCRYPT_MODE_NOFB, $key = "mySecretKey", $encrypted = "encryptedText")
    {
        $key_size = mcrypt_module_get_algo_key_size($algorithm);
        $iv_size = mcrypt_get_iv_size($algorithm, $mode);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $key = substr($key, 0, $key_size);

        return mcrypt_decrypt($algorithm, $key, $cyphered, $mode, $iv);
    }
Exemple #3
0
 public function testBase64Mode()
 {
     $algo = Mcrypt::ALGO_DES;
     $mode = Mcrypt::MODE_ECB;
     $key = Mcrypt::createRandomKey(mcrypt_module_get_algo_key_size($algo));
     $iv = Mcrypt::createRandomIv(mcrypt_get_iv_size($algo, $mode));
     $mcrypt = new Mcrypt($key, $iv, $algo, $mode);
     $mcrypt->setBase64Mode(false);
     $encrypted = $mcrypt->encrypt('foo');
     $this->assertSame(base64_encode($encrypted), $mcrypt->setBase64Mode(true)->encrypt('foo'));
 }
Exemple #4
0
 /**
  * Checks if a key is valid for {@link cryptAlgorithm}.
  * @param string $key the key to check
  * @return boolean the validation result
  * @throws CException if the supported key lengths of the cipher are unknown
  */
 protected function validateEncryptionKey($key)
 {
     if (is_string($key)) {
         $supportedKeyLengths = mcrypt_module_get_supported_key_sizes($this->cryptAlgorithm);
         if ($supportedKeyLengths) {
             if (!in_array($this->strlen($key), $supportedKeyLengths)) {
                 throw new CException(Yii::t('yii', 'Encryption key length can be {keyLengths}.', array('{keyLengths}' => implode(',', $supportedKeyLengths))));
             }
         } elseif (isset(self::$encryptionKeyMinimumLengths[$this->cryptAlgorithm])) {
             $minLength = self::$encryptionKeyMinimumLengths[$this->cryptAlgorithm];
             $maxLength = mcrypt_module_get_algo_key_size($this->cryptAlgorithm);
             if ($this->strlen($key) < $minLength || $this->strlen($key) > $maxLength) {
                 throw new CException(Yii::t('yii', 'Encryption key length must be between {minLength} and {maxLength}.', array('{minLength}' => $minLength, '{maxLength}' => $maxLength)));
             }
         } else {
             throw new CException(Yii::t('yii', 'Failed to validate key. Supported key lengths of cipher not known.'));
         }
     } else {
         throw new CException(Yii::t('yii', 'Encryption key should be a string.'));
     }
 }
Exemple #5
0
 /**
  * @return int
  */
 public function getMaxKeySize()
 {
     return mcrypt_module_get_algo_key_size($this->getAlgorithm());
 }
Exemple #6
0
 public function generateSessionKey()
 {
     $key = '';
     if (!empty($this->cryptParams['cipher']) && !empty($this->cryptParams['mode'])) {
         $keysize = mcrypt_module_get_algo_key_size($this->cryptParams['cipher']);
         /* Generating random key using iv generation routines */
         if ($keysize > 0 && ($td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', $this->cryptParams['mode'], ''))) {
             if ($this->cryptParams['cipher'] == MCRYPT_RIJNDAEL_128) {
                 $keysize = 16;
                 if ($this->type == XMLSecurityKey::AES256_CBC) {
                     $keysize = 32;
                 } elseif ($this->type == XMLSecurityKey::AES192_CBC) {
                     $keysize = 24;
                 }
             }
             while (strlen($key) < $keysize) {
                 $key .= mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
             }
             mcrypt_module_close($td);
             $key = substr($key, 0, $keysize);
             $this->key = $key;
         }
     }
     return $key;
 }
 /**
  * Generate the private key to use for encryption/decryption
  * 
  * @param array $params
  * @return array $params
  */
 private function GeneratePrivateKey($params)
 {
     // Max size for the key by chosen algorhythm
     $size = mcrypt_module_get_algo_key_size($params["cipher"]);
     // reduce key to max. size supported
     $params["private_key"] = substr($params["public_key"], 0, $size);
     return $params;
 }
<?php

var_dump(mcrypt_module_get_algo_key_size(MCRYPT_RIJNDAEL_256));
var_dump(mcrypt_module_get_algo_key_size(MCRYPT_RIJNDAEL_192));
var_dump(mcrypt_module_get_algo_key_size(MCRYPT_RC2));
var_dump(mcrypt_module_get_algo_key_size(MCRYPT_XTEA));
var_dump(mcrypt_module_get_algo_key_size(MCRYPT_CAST_128));
var_dump(mcrypt_module_get_algo_key_size(MCRYPT_BLOWFISH));
 /**
  * This method encrypts data and returns a CipherText object. You need it to decrypt the data back.
  *
  * @param string $cipher The cipher algorithm to use.
  * @param mixed $plainText The plaintext to encrypt.
  * @param binary $key An optional key. If not specified, PSL will generate it and return it within CipherText.
  * @param string $operationMode The cipher mode of operation to use. Defaults to CBC.
  * @param binary $iv An optional parameter. PSL will generate it if not given and return it within CipherText.
  * @throws Exception
  * @return \PSL\CipherText
  */
 public static function encrypt($cipher, $plainText, $key = null, $operationMode = 'cbc', $iv = null)
 {
     $operationMode = strtolower($operationMode);
     // If the key is null, we generate it on ourself.
     if ($key === null) {
         // Check whether the cipher is supported.
         $supportedCiphers = self::getSupportedCiphers();
         if (in_array($cipher, $supportedCiphers) === false) {
             throw new Exception("The cipher '{$cipher}' is not supported on this system. The following is a list of supported ciphers: " . implode(', ', $supportedCiphers));
         }
         // We will use the maximum strength.
         $length = mcrypt_module_get_algo_key_size($cipher);
         $key = Randomizer::getRandomBytes($length);
     }
     // Make sure we can actually encrypt with these details. Be strict.
     self::isCipherable($cipher, $key, $operationMode, true);
     // If the developer did not specify an IV, we generate a strong pseudo random one.
     if ($iv === null) {
         if (($ivSize = @mcrypt_get_iv_size($cipher, $operationMode)) === false) {
             throw new Exception("Could not retrieve an IV size for cipher '{$cipher}' using a operation mode '{$operationMode}'.");
         }
         $iv = Randomizer::getRandomBytes($ivSize);
     }
     // Padding for block cipher modes such as CBC and ECB.
     $padded = false;
     if (mcrypt_module_is_block_mode($operationMode) === true) {
         $padded = true;
         // Calculate how many bytes we need to add.
         $addBytes = $ivSize - strlen((string) $plainText) % $ivSize;
         if ($addBytes === 0) {
             // Important.
             $addBytes = $ivSize;
         }
         // Pad with chr($addBytes).
         $plainText .= str_repeat(chr($addBytes), $addBytes);
     }
     // The encryption.
     if (($cipherText = @mcrypt_encrypt($cipher, $key, $plainText, $operationMode, $iv)) === false) {
         throw new Exception("Could not encrypt with a cipher '{$cipher}' using a operation mode '{$operationMode}'.");
     }
     // Building the object with the right properties and returning it.
     $ct = new CipherText();
     $ct->cipherText = $cipherText;
     $ct->iv = $iv;
     $ct->operationMode = $operationMode;
     $ct->cipher = $cipher;
     $ct->key = $key;
     $ct->padded = $padded;
     // In case some one needs to know this.
     return $ct;
 }
 public static function decrypt($val, $key = 'siteenligne', $iv = 'hmco3773')
 {
     $key_size = mcrypt_module_get_algo_key_size(MCRYPT_BLOWFISH);
     $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_NOFB);
     $key = substr($key, 0, $key_size);
     $crypte = urldecode($val);
     $crypte = base64_decode($crypte);
     $crypte = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $crypte, MCRYPT_MODE_NOFB, $iv);
     return $crypte;
 }
Exemple #11
0
<?php

// normal usage of mcrypt
mcrypt_module_get_algo_key_size($c);
// no mcrypt usage
$mcrypt_create_iv = 2;
$x = 'mcrypt_enc_is_block_algorithm_mode';
Exemple #12
0
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);
$key = substr(md5("very secret key"), 0, $ks);
mcrypt_generic_init($td, $key, $iv);
$encrypted = mcrypt_generic($td, "This is very important data");
VERIFY($encrypted !== "This is very important data");
mcrypt_generic_deinit($td);
mcrypt_generic_init($td, $key, $iv);
$decrypted = mdecrypt_generic($td, $encrypted);
mcrypt_generic_end($td);
mcrypt_module_close($td);
VS($decrypted, "This is very important data");
VERIFY(in_array("blowfish", mcrypt_list_algorithms()));
VERIFY(in_array("cbc", mcrypt_list_modes()));
VS(mcrypt_module_get_algo_block_size("blowfish"), 8);
VS(mcrypt_module_get_algo_key_size("blowfish"), 56);
VS(mcrypt_module_get_supported_key_sizes("blowfish"), array());
VS(mcrypt_module_get_supported_key_sizes("twofish"), array(16, 24, 32));
VS(mcrypt_module_is_block_algorithm_mode("cbc"), true);
VS(mcrypt_module_is_block_algorithm("blowfish"), true);
VS(mcrypt_module_is_block_mode("cbc"), true);
VS(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128), true);
VS(mcrypt_module_self_test("bogus"), false);
$text = "boggles the inivisble monkey will rule the world";
$key = "very secret key";
$iv_size = mcrypt_get_iv_size(MCRYPT_XTEA, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$enc = mcrypt_encrypt(MCRYPT_XTEA, $key, $text, MCRYPT_MODE_ECB, $iv);
VS(bin2hex($enc), "f522c62002fa16129c8576bcddc6dd0f7ea81991103ba42962d94c8bfff3ee660d53b187d7e989540abf5a729c2f7baf");
$crypttext = mcrypt_decrypt(MCRYPT_XTEA, $key, $enc, MCRYPT_MODE_ECB, $iv);
VS($crypttext, $text);
Exemple #13
0
function plugin_accounts_crypte($Texte, $action)
{
    //$algo = "blowfish"; // ou la constante php MCRYPT_BLOWFISH
    //$mode = "nofb"; // ou la constante php MCRYPT_MODE_NOFB
    $key_size = mcrypt_module_get_algo_key_size(MCRYPT_RIJNDAEL_256);
    //$iv_size = mcrypt_get_iv_size($algo, $mode);
    //$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $key = 'Ceci est une clé secrète';
    if ($action == 1) {
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $Texte, MCRYPT_MODE_ECB, $iv);
        $crypttext = base64_encode($crypttext);
    } else {
        if ($action == 2) {
            $crypttext = "<script language='javascript'>document.write(AESEncryptCtr({$Texte},SHA256({$key}),256));</script>";
        } else {
            if ($action == 3) {
                $Texte = base64_decode($Texte);
                $crypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $Texte, MCRYPT_MODE_ECB, $iv);
            }
        }
    }
    return trim($crypttext);
}
<?php

$algorithms = mcrypt_list_algorithms();
printf("%-18s %s %8s\n", "算法名", "最大支持密钥长度(字节)", "分组(block)/流式(stream)");
foreach ($algorithms as $cipher) {
    $max_key_size = mcrypt_module_get_algo_key_size($cipher);
    $stream_mode = mcrypt_module_is_block_algorithm($cipher) == TRUE ? "block" : "stream";
    printf("%-18s %3d %25s\n", $cipher, $max_key_size, $stream_mode);
}