Implementation method of DES encryption and decryption in PHP and. NET _php instance

Source: Internet
Author: User
Tags decrypt flush strlen

php5.x version, to add PHP extension php_mcrypt.

PHP Version:

Copy Code code as follows:

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

/**
* Constructs, passing two key and IV which have been base64_encode
*
* @param string $key
* @param string $iv
*/
function __construct ($key, $iv)
{
if (Empty ($key) | | empty ($IV)) {
Echo ' key ' and ' IV ' not valid ';
Exit ();
}
$this->key = $key;
$this->iv = $iv;
}

/**
* Encryption
* @param <type> $value
* @return <type>
*/
Public function Encrypt ($value)
{
$TD = Mcrypt_module_open (Mcrypt_3des, ', MCRYPT_MODE_CBC, ');
$iv = Base64_decode ($this->iv);
$value = $this-&GT;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 <type> $value
* @return <type>
*/
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-&GT;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));
$rs 1= $des->encrypt ($msg);
echo $rs 1. ' <br/> ';
$rs 2= $des->decrypt ($rs 1);
echo $rs 2;

. NET version

Copy Code code as follows:

Sealed public class Cryptohelper
{
<summary>
Encrypts the specified input.
</summary>
<param name= "Input" >the input.</param>
<param name= "Key" >key</param>
<param name= "IV" >iv</param>
<returns></returns>
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 the
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;
}
<summary>
Decrypts the specified input.
</summary>
<param name= "Input" >the input.</param>
<param name= "Key" >key</param>
<param name= "IV" >iv</param>
<returns></returns>
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 isn't 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 the
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));

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.