如何利Mcrypt擴展庫進行加密和解密

發表于:2007-07-14來源:作者:點擊數: 標簽:
綜述:Mcrypt 2.4.7是一個功能強大的加密算法擴展庫,它包括有22種算法,其中就包括下面的幾種算法: ????Blowfish RC2 Safer-sk64 xtea ????Cast-256 RC4 Safer-sk128 ????DES RC4-iv Serpent ????Enigma Rijndael-128 Threeway ????Go
綜述:Mcrypt 2.4.7是一個功能強大的加密算法擴展庫,它包括有22種算法,其中就包括下面的幾種算法:

????Blowfish RC2 Safer-sk64 xtea
????Cast-256 RC4 Safer-sk128
????DES RC4-iv Serpent
????Enigma Rijndael-128 Threeway
????Gost Rijndael-192 TripleDES
????LOKI97 Rijndael-256 Twofish
????PanamaSaferplus Wake

??如何安裝Mcrypt?

??在標準的PHP軟件包中不包括Mcrypt,因此需要下載它,下載的地址為:ftp://argeas.cs-net.gr/pub/unix/mcrypt/ 。下載后,按照下面的方法進行編譯,并把它擴充在PHP中:

??下載Mcrypt軟件包。

????gunzipmcrypt-x.x.x.tar.gz
????tar -xvfmcrypt-x.x.x.tar
????./configure --disable-posix-threads
????make
????make install
????cd to your PHP directory.
????./configure -with-mcrypt=[dir] [--other-configuration-directives]
????make
????make install

??根據你的要求和PHP安裝時與服務器作適當的修改。

??如何使用Mcrypt擴展庫對數據進行加密?

??首先,我們將介紹如何使用Mcrypt擴展庫對數據進行加密,然后再介紹如何使用它進行解密。下面的代碼對這一過程進行了演示,首先是對數據進行加密,然后在瀏覽器上顯示加密后的數據,并將加密后的數據還原為原來的字符串,將它顯示在瀏覽器上。

??使用Mcrypt對數據進行加、解密

????<?php
????// Designate string to be encrypted
????$string = "Applied Cryptography, by Bruce Schneier, is
????a 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,
????MCRYPT_MODE_ECB), MCRYPT_RAND);

????// Output original string
????print "Original string: $string
";

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

????// Convert to hexadecimal and output to browser
????print "Encrypted string: ".bin2hex($encrypted_string)."

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

????print "Decrypted string: $decrypted_string";
?????>


??執行上面的腳本將會產生下面的輸出:

????Original string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.

????Encrypted string: 02a7c58b1ebd22a9523468694b091e60411clearcase/" target="_blank" >cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b c89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e

????Decrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.


??上面的代碼中兩個最典型的函數是mcrypt_encrypt()和 mcrypt_decrypt(),它們的用途是顯而易見的。我們使用了"電報密碼本"模式,Mcrypt提供了幾種加密方式,由于每種加密方式都有可以影響密碼安全的特定字符,因此對每種模式都需要了解。對那些沒有接觸過密碼系統的讀者來說,可能對mcrypt_create_iv()函數更有興趣,我們會提到它創建的初始化向量(hence, iv),這一向量可以使每條信息彼此獨立。 盡管不是所有的模式都需要這一初始化變量,但如果在要求的模式中沒有提供這一變量,PHP就會給出警告信息。

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97