triple_des(des3) 算法 - php,python 实现

调用电信那边的接口. 要用到 triple_des 加密算法. 整了python 和 php 两个版本的实现.

iv, key 变量指向的都是 hex 字符串.

php:

 

#!/usr/bin/php
<?php

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;
}

function fmt3DESEx($data, $key, $iv) {
	$td = mcrypt_module_open(MCRYPT_3DES,"", MCRYPT_MODE_CBC, "");
	$key = pack("H48",$key);
	$iv = pack("H16",$iv);
	mcrypt_generic_init($td, $key, $iv);
	$data = PaddingPKCS7($data);
	$desResult = mcrypt_generic($td, $data);
	mcrypt_generic_deinit($td);
	mcrypt_module_close($td);
	return base64_encode($desResult);     
}



$data = "asdf";
$key = "313233343536373839303132333435363738393031323334";
$iv = "3132333435363738";
$code = fmt3DESEx(mhash(MHASH_SHA1,$data), $key, $iv);
echo $code;
?>

python:

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import binascii
import hashlib
import base64
import pyDes

iv = '3132333435363738'
key = '313233343536373839303132333435363738393031323334'
data = "asdf"

iv = binascii.unhexlify(iv)
key = binascii.unhexlify(key)
data = hashlib.sha1(data)

k = pyDes.triple_des(key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
d = k.encrypt(data.digest())
print base64.encodestring(d)