We will use DES CBC encryption. The following are the example of DES Encrypt/Decrypt function:
ASP.Net version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
protected byte[] EncryptKey = ASCIIEncoding.ASCII.GetBytes("ask_us_for_key"); public string DESEncrypt(string inString) { MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, new DESCryptoServiceProvider().CreateEncryptor(EncryptKey, EncryptKey), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cs); sw.Write(inString); sw.Flush(); cs.FlushFinalBlock(); sw.Flush(); return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } public string DESDecrypt(string inString) { try { return new StreamReader(new CryptoStream(new MemoryStream( Convert.FromBase64String(inString)), new DESCryptoServiceProvider().CreateDecryptor(EncryptKey, EncryptKey), CryptoStreamMode.Read)).ReadToEnd(); } catch { } return ""; } |
PHP version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php class DES { var $key; var $iv; function __construct( $key, $iv=0 ) { $this->key = $key; if( $iv == 0 ) { $this->iv = $key; } else { $this->iv = $iv; } } function encrypt($str) { return base64_encode( openssl_encrypt($str, 'DES-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv ) ); } function decrypt($str) { $str = openssl_decrypt(base64_decode($str), 'DES-CBC', $this->key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $this->iv); return rtrim($str, "x01..x1F"); } function pkcs5Pad($text, $blocksize) { $pad = $blocksize - (strlen ( $text ) % $blocksize); return $text . str_repeat ( chr ( $pad ), $pad ); } } ?> |