note 52833 deleted from function.mcrypt-encrypt by tularis
| From: | tularis@php.net | Date: | Sat, 14 May 2005 16:34:03 +0000 |
| Subject: | note 52833 deleted from function.mcrypt-encrypt by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-89426@lists.php.net to get a copy of this message | ||
Note Submitter: OrionI
Reason: useless
----
Here's a complete example that works for encrypting some plain ascii text in .NET and
decrypting it in PHP. I use base64 encoding to transport the encrypted data since it uses a fairly
standard set of characters. Make your own custom IV value if you want. If you're testing out
mcrypt on Windows, be sure to get the libmcrypt.dll file mentioned at the top of http://www.php.net/mcrypt - it doesn't come with the PHP
zip file.
//C# code
using System.Security.Cryptography;
using System.Text;
...
public static string TripleDESEncrypt(string Plaintext, string Key)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Key));
DES.Mode = CipherMode.CBC;
DES.IV = Convert.FromBase64String("32h4k1Ysu+A=");
DES.Padding=PaddingMode.Zeros;
ICryptoTransform DESEncrypt = DES.CreateEncryptor(DES.Key,DES.IV);
byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(Plaintext);
byte[] result = DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length);
return Convert.ToBase64String(result);
}
<?php
//PHP function
function TripleDesDecrypt($base64encoded, $key)
{
$encryptedbinary = base64_decode($base64encoded);
$md5key = md5($key);
//extend it to 192 bits to match .NET (see comment below)
$md5key .= substr($md5key,0,16);
$binarykey = pack('H*',$md5key);
$iv = base64_decode("32h4k1Ysu+A=");
return rtrim(mcrypt_decrypt(MCRYPT_TRIPLEDES, $binarykey, $encryptedbinary, MCRYPT_MODE_CBC, $iv));
}
?>
To use it, say in an ASP.NET application, do something like this...
//C#
...
string sensitive = "Important info!";
string key = "topsecret555";
string redirecturl = "decrypt.php?encryptedvalue=" +
Server.UrlEncode(TripleDESEncrypt(sensitive, key));
Response.Redirect(redirecturl);
...
Then, in PHP,
<?php
$encrypted = urldecode($_GET["encryptedvalue"]);
$key = "topsecret555";
$decrypted = TripleDesDecrypt($encrypted, $key);
echo $decrypted;
...
?>