Implementation of des encryption and decryption in PHP and. net _ PHP Tutorial

Source: Internet
Author: User
Implementation of des encryption and decryption in PHP and. net. In php5.x, add the php extension php_mcrypt. PHP version: The copy code is as follows: classSTD3Des {private $ key; private $ iv; *** structure. two base php5.x versions are passed. you need to add the php extension php_mcrypt.

PHP version:

The code is as follows:


Class STD3Des
{
Private $ key = "";
Private $ iv = "";

/**
* Construct and pass two keys and IV that have been base64_encode
*
* @ Param string $ key
* @ Param string $ iv
*/
Function _ construct ($ key, $ iv)
{
If (empty ($ key) | empty ($ iv )){
Echo 'key and iv is not valid ';
Exit ();
}
$ This-> key = $ key;
$ This-> iv = $ iv;
}

/**
* Encryption
* @ Param $ Value
* @ Return
*/
Public function encrypt ($ value)
{
$ Td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC ,'');
$ Iv = base64_decode ($ this-> iv );
$ Value = $ this-> PaddingPKCS7 ($ value );
$ Key = base64_decode ($ this-> key );
Mcrypt_generic_init ($ td, $ key, $ iv );
$ Ret = base64_encode (mcrypt_generic ($ td, $ value ));
Mcrypt_generic_deinit ($ td );
Mcrypt_module_close ($ td );
Return $ ret;
}

/**
* Decryption
* @ Param $ Value
* @ Return
*/
Public function decrypt ($ value)
{
$ Td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC ,'');
$ Iv = base64_decode ($ this-> iv );
$ Key = base64_decode ($ this-> key );
Mcrypt_generic_init ($ td, $ key, $ iv );
$ Ret = trim (mdecrypt_generic ($ td, base64_decode ($ value )));
$ Ret = $ this-> UnPaddingPKCS7 ($ ret );
Mcrypt_generic_deinit ($ td );
Mcrypt_module_close ($ td );
Return $ ret;
}

Private function PaddingPKCS7 ($ data)
{
$ Block_size = mcrypt_get_block_size ('tripledes ', 'cbc ');
$ Padding_char = $ block_size-(strlen ($ data) % $ block_size );
$ Data. = str_repeat (chr ($ padding_char), $ padding_char );
Return $ data;
}

Private function UnPaddingPKCS7 ($ 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 );
}
}


// Use
Include ('std3des. class. php ');
$ Key = 'abcdefgh ';
$ Iv = 'abcdefgh ';
$ Msg = 'Test string ';
$ Des = new STD3Des (base64_encode ($ key), base64_encode ($ iv ));
$ Rs1 = $ des-> encrypt ($ msg );
Echo $ rs1 .'
';
$ Rs2 = $ des-> decrypt ($ rs1 );
Echo $ rs2;

. Net version

The code is as follows:


Sealed public class CryptoHelper
{
///


/// Encrypts the specified input.
///
/// The input.
/// Key
/// Iv
///
Public static string EncryptDes (string input, byte [] key, byte [] iv)
{
If (input = null | input. Length = 0)
Return String. Empty;

DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
MemoryStream MS = null;
CryptoStream encStream = null;
StreamWriter sw = null;
String result = String. Empty;

Try
{
MS = new MemoryStream ();

// Create a CryptoStream using the memory stream and
// Csp des key.
// Des. Mode = CipherMode. CBC;
// Des. Padding = PaddingMode. PKCS7;
EncStream = new CryptoStream (MS, des. CreateEncryptor (key, iv), CryptoStreamMode. Write );

// Create a StreamWriter to write a string
// To the stream.
Sw = new StreamWriter (encStream );

// Write the plaintext to the stream.
Sw. Write (input );

Sw. Flush ();
EncStream. FlushFinalBlock ();
Ms. Flush ();


Result = Convert. ToBase64String (ms. GetBuffer (), 0, Convert. ToInt32 (ms. Length, CultureInfo. InvariantCulture ));
}
Finally
{
// Close objects
If (sw! = Null)
Sw. Close ();
If (encStream! = Null)
EncStream. Close ();
If (MS! = Null)
Ms. Close ();
}

// Return the encrypted string
Return result;
}
///
/// Decrypts the specified input.
///
/// The input.
/// Key
/// Iv
///
Public static string DecryptDes (string input, byte [] key, byte [] iv)
{
Byte [] buffer;
Try {buffer = Convert. FromBase64String (input );}
Catch (System. ArgumentNullException) {return String. Empty ;}
// Length is zero, or not an even multiple of four (plus a few other cases)
Catch (System. FormatException) {return String. Empty ;}

DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
MemoryStream MS = null;
CryptoStream encStream = null;
StreamReader sr = null;
String result = String. Empty;

Try
{
MS = new MemoryStream (buffer );

// Create a CryptoStream using the memory stream and
// Csp des key.
EncStream = new CryptoStream (MS, des. CreateDecryptor (key, iv), CryptoStreamMode. Read );

// Create a StreamReader for reading the stream.
Sr = new StreamReader (encStream );

// Read the stream as a string.
Result = sr. ReadToEnd ();
}
Finally
{
// Close objects
If (sr! = Null)
Sr. Close ();
If (encStream! = Null)
EncStream. Close ();
If (MS! = Null)
Ms. Close ();
}

Return result;
}
}


// Call

String key = "abcdefgh ";
String iv = "abcdefgh ";
String msg = "test string ";
String rs1 = CryptoHelper. EncryptDes (msg, System. Text. Encoding. ASCII. GetBytes (key), System. Text. Encoding. ASCII. GetBytes (iv ));
String rs2 = CryptoHelper. DecryptDes (rs1, System. Text. Encoding. ASCII. GetBytes (key), System. Text. Encoding. ASCII. GetBytes (iv ));

Bytes. PHP version: the code is as follows: class STD3Des {private $ key = ""; private $ iv = "";/*** structure, passed two base...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.