开发者

DES encryption in PHP

I am coding a Drupal payment method module and within this I need to generate a hash to send to a bank. Bank asks me to code certain strings into the DES/ECB hash. They also provide test environment and here comes my problem. With the string B7DC02D5D6F2689E and key 7465737465703031 I should get result hash 3627C7356B25922B (after bin2hex, of course). This is by the bank test page and I have also checked this on this page: http://www.riscure.com/tech-corner/online-crypto-tools/des.html (encryption java applet).

My problem is that whatever I do I cant get my PHP code to provide the correct result. This is a simple function I am trying to use:

function encrypt($hash, $key)
{
$hash = strtoupper(substr(sha1($hash), 0, 16));
$key = strtoupper(bin2hex($key));

$block = mcrypt_get_block_size('des', 'ecb');
if (($pad = $block - (strlen($hash) % $block)) < $block) {
  $hash .= str_repeat(chr($pad), $pad);
}

$sig = strtoupper(bin2hex(mcrypt_encrypt(MCRYPT_DES, $key, $hash, MCRYPT_MODE_ECB)));
return $sig;
}

and I have been trying sth like this as well:

function encrypt( $value, $key) {
$hash = strtoupper(substr(sha1($value), 0, 16));
$key = strtoupper(substr(bin2hex($key), 0, 16));
// encrypt hash with key
if (function_exists('mcrypt_module_open')) {         // We have mcrypt 2.4.x
  $td = mcrypt_module_open(MCRYPT_DES, "", MCRYPT_MODE_ECB, "");
  $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
  mcrypt_generic_init($td, $key, $iv);
  $signature = strtoupper(bin2hex(mcrypt_generic ($td, $hash)));
  mcrypt_generic_end ($td);
}
else
{                        // We have 2.2.x only
$signature = strtoupper(bin2hex(mcrypt_ecb (MCRYPT_3DES, $key, $hash, MCRYPT_ENCRYPT)));
}
return $signature;
}

None of these gave the correct signature. Any idea what's wrong? For now I am dealing with this issue more than 3 hrs, so I appreciate any help. I am not very familiar with this encryption stuff. Thanks a lot.

Btw.: Those $hash and $key mentioned above 开发者_如何转开发are after the strtoupper, substr and bin2hex functions at the beginning of my code snippets.


Simple solution:

function encrypt($hash, $key) {
    return mcrypt_encrypt("des", pack("H*", $key), pack("H*", $hash), "ecb");
}

print bin2hex(encrypt("B7DC02D5D6F2689E", "7465737465703031"));

This prints 3627c7356b25922b for me, so it looks like that's working.

You were on the right track with bin2hex(), but that was converting in the wrong direction. (There's unfortunately no hex2bin() function, so you have to use pack() instead.)

You also don't need an IV for a single-block encryption like this.


You plaintext, B7DC02D5D6F2689E, is 8 bytes = 64 bits. This is an exact block for DES so you don't need any padding in ECB mode. I suggest that you remove the padding code entirely. All DEC-ECB needs in this case is the block to encrypt and the key; no padding and no IV.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜