I have a DES Algorithm use java ,now I need convert this java program for php, I don't know java cipher.init
method's third parameters SecureRandom
,So I use my php Des program to encrypt a string ,but I got a different result with java Des.
Here is my Java DES:
public static String encode(String srcStr) {
if (srcStr == null)
return null;
String dst = null;
byte[] result = encrypt2(srcStr.getBytes(), "h43au76U");
if (result == null)
return null;
System.out.println(result);
dst = byte2HexStr(result, result.length);
return dst;
}
private static final char[] mChars = "0123456789ABCDEF".toCharArray();
public static String byte2HexStr(byte[] b, int iLen) {
if (b == null)
return null;
StringBuilder sb = new StringBuilder();
for (int n = 0; n < iLen; n++) {
sb.append(mChars[(b[n] & 0xff) >> 4]);
sb.append(mChars[b[n] & 0xf]);
}
return sb.toString().trim().toUpperCase(Locale.US);
}
private static byte[] encrypt2(byte[] datasource, String password) {
byte[] is;
try {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
javax.crypto.SecretKey securekey
= keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(1, securekey, random);
is = cipher.doFinal(datasource);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
return is;
}
And this is my php des:
function encrypt($input,$key,$iv=0){
$size = mcrypt_get_block_size(MCRYPT_DES,MCRYPT_MODE_CBC); //3DES加密将MCRYPT_DES改为MCRYPT_3DES
$input =pkcs5_pad($input, $size); //如果采用PaddingPKCS7,请更换成PaddingPKCS7方法。
$td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
@mcrypt_generic_init($td, $key,$iv);
$data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
// return $data;
return strtoupper(bin2hex($data));
}
I got a different result, why? And I don't know if SecureRandom is a iv
?