Class DES { Var $ key; Var $ iv; // Offset Function DES ($ key = '000000', $ iv = 0 ){ // The key length is 8, for example, 1234 abcd. $ This-> key = $ key; If ($ iv = 0 ){ $ This-> iv = $ key; // $ key is used as the iv by default. } Else { $ This-> iv = $ iv; // mcrypt_create_iv (mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM ); } } Function encrypt ($ str ){ // Encrypted, returns an uppercase hexadecimal string $ Size = mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC ); $ Str = $ this-> pkcs5Pad ($ str, $ size ); Return strtoupper (bin2hex (mcrypt_cbc (MCRYPT_DES, $ this-> key, $ str, MCRYPT_ENCRYPT, $ this-> iv ))); } Function decrypt ($ str ){ // Decrypt $ StrBin = $ this-> hex2bin (strtolower ($ str )); $ Str = mcrypt_cbc (MCRYPT_DES, $ this-> key, $ strBin, MCRYPT_DECRYPT, $ this-> iv ); $ Str = $ this-> pkcs5Unpad ($ str ); Return $ str; } Function hex2bin ($ hexData ){ $ BinData = ""; For ($ I = 0; $ I <strlen ($ hexData); $ I + = 2 ){ $ BinData. = chr (hexdec (substr ($ hexData, $ I, 2 ))); } Return $ binData; } Function pkcs5Pad ($ text, $ blocksize ){ $ Pad = $ blocksize-(strlen ($ text) % $ blocksize ); Return $ text. str_repeat (chr ($ pad), $ pad ); } Function pkcs5Unpad ($ text ){ $ Pad = ord ($ text {strlen ($ text)-1 }); If ($ pad> strlen ($ text )) Return false; If (strspn ($ text, chr ($ pad), strlen ($ text)-$ pad )! = $ Pad) Return false; Return substr ($ text, 0,-1 * $ pad ); } } ?> |