如何利Mcrypt扩展库进行加密和解密

网络整理 - 08-17

综述:Mcrypt 2.4.7是一个功能强大的加密算法扩展库,它包括有22种算法,其中就包括下面的几种算法:

以下为引用的内容:
牐燘lowfish RC2 Safer-sk64 xtea
牐牐牐燙ast-256 RC4 Safer-sk128
牐牐牐燚ES RC4-iv Serpent
牐牐牐燛nigma Rijndael-128 Threeway
牐牐牐燝ost Rijndael-192 TripleDES
牐牐牐燣OKI97 Rijndael-256 Twofish
牐牐牐燩anamaSaferplus Wake 

如何安装Mcrypt?

在标准的PHP软件包中不包括Mcrypt,因此需要下载它,下载的地址为:ftp://argeas.cs-net.gr/pub/unix/mcrypt/ 。下载后,按照下面的方法进行编译,并把它扩充在PHP中:

下载Mcrypt软件包。

以下为引用的内容:
               gunzipmcrypt-x.x.x.tar.gz
牐牐牐爐ar -xvfmcrypt-x.x.x.tar
牐牐牐./configure --disable-posix-threads
牐牐牐爉ake
牐牐牐爉ake install
牐牐牐燾d to your PHP directory.
牐牐牐./configure -with-mcrypt=[dir] [--other-configuration-directives]
牐牐牐爉ake
牐牐牐爉ake install 

根据你的要求和PHP安装时与服务器作适当的修改。

如何使用Mcrypt扩展库对数据进行加密?

首先,我们将介绍如何使用Mcrypt扩展库对数据进行加密,然后再介绍如何使用它进行解密。下面的代码对这一过程进行了演示,首先是对数据进行加密,然后在浏览器上显示加密后的数据,并将加密后的数据还原为原来的字符串,将它显示在浏览器上。

使用Mcrypt对数据进行加、解密

以下为引用的内容:
牐牐牐?php
牐牐牐// Designate string to be encrypted
牐牐牐$string = "Applied Cryptography, by Bruce Schneier, is
牐牐牐燼 wonderful cryptography reference.";

牐牐牐// Encryption/decryption key
牐牐牐$key = "Four score and twenty years ago";

牐牐牐// Encryption Algorithm
牐牐牐$cipher_alg = MCRYPT_RIJNDAEL_128;

牐牐牐// Create the initialization vector for added security.
牐牐牐$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,
牐牐牐燤CRYPT_MODE_ECB), MCRYPT_RAND);

牐牐牐// Output original string
牐牐牐爌rint "Original string: $string
";

牐牐牐// Encrypt $string
牐牐牐$encrypted_string = mcrypt_encrypt($cipher_alg, $key,
牐牐牐$string, MCRYPT_MODE_CBC, $iv);

牐牐牐// Convert to hexadecimal and output to browser
牐牐牐爌rint "Encrypted string: ".bin2hex($encrypted_string)."

";
牐牐牐$decrypted_string = mcrypt_decrypt($cipher_alg, $key,
牐牐牐$encrypted_string, MCRYPT_MODE_CBC, $iv);

牐牐牐爌rint "Decrypted string: $decrypted_string";
牐牐牐?> 

执行上面的脚本将会产生下面的输出:

以下为引用的内容:
牐牐燨riginal string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.

牐牐牐燛ncrypted string: 02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b c89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e

牐牐牐燚ecrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference. 

上面的代码中两个最典型的函数是mcrypt_encrypt()和 mcrypt_decrypt(),它们的用途是显而易见的。我们使用了"电报密码本"模式,Mcrypt提供了几种加密方式,由于每种加密方式都有可以影响密码安全的特定字符,因此对每种模式都需要了解。对那些没有接触过密码系统的读者来说,可能对mcrypt_create_iv()函数更有兴趣,我们会提到它创建的初始化向量(hence, iv),这一向量可以使每条信息彼此独立。 尽管不是所有的模式都需要这一初始化变量,但如果在要求的模式中没有提供这一变量,PHP就会给出警告信息。