Skip to content

Instantly share code, notes, and snippets.

@MichaelPaulukonis
Created September 10, 2013 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelPaulukonis/6510260 to your computer and use it in GitHub Desktop.
Save MichaelPaulukonis/6510260 to your computer and use it in GitHub Desktop.
TripleDES encryption in PHP (using unique initialization vector (iv)), used when encrypting in PHP and decrypting in C#
<?php
/*
Based on code from the following sources:
http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html
http://www.sanity-free.org/forum/viewtopic.php?id=133
http://php.net/manual/en/function.mcrypt-encrypt.php
See Also:
http://php.net/manual/en/function.mcrypt-create-iv.php
http://stackoverflow.com/questions/5108408/php-mcrypt-which-mode
*/
$buffer = "123456";
# get the amount of bytes to pad
$extra = 8 - (strlen($buffer) % 8);
# add the zero padding
if($extra > 0) {
for($i = 0; $i < $extra; $i++) {
$buffer .= "\0";
}
}
# needless to say, you should use a unique key
# this is from the primary code source (see above)
$key = "passwordDR0wSS@P6660juht";
# create a random Initialization Vector (iv)
$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_NOFB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
# hex encode the return value
$crypted = bin2hex(mcrypt_cbc(MCRYPT_3DES, $key, $buffer, MCRYPT_ENCRYPT, $iv));
# this is a simple example
echo "Result: $crypted iv: ".bin2hex($iv);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment