3
我知道有相當多的討論圍繞計算器關於PHP的Java AES CBC加密的,但它們都沒有解決我的問題使用PHP來獲得相同的AES-128-CBC加密,Java並
這裏是用java功能:
public static String encrypt(String input, String key){
byte[] crypted = null;
SecretKeySpec skey = new SecretKeySpec(getHash("MD5", key), "AES");
IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
crypted = cipher.doFinal(input.getBytes());
return new String(Base64.encodeBase64(crypted));
}
private static byte[] getHash(String algorithm, String text) {
try {
byte[] bytes = text.getBytes("UTF-8");
final MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(bytes);
return digest.digest();
} catch (final Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
以下是我在PHP
所做public static function encrypt($input, $key) {
$key = hash('md5', $key, true);
$iv = '0000000000000000';
return openssl_encrypt($input, 'aes-128-cbc', $key, 0, $iv);
}
讓我們看看結果
key:"790757e76c8942f995675b247aa57c2a"
input:"1234"
result in java:UfczMtIAm8ewSuIGRdPTDQ==
result in PHP:wd/OTHoIXwgHGDHcj8OTgg==
在PHP中,我也有使用其他方法,如mcrypt_encrypt
,mcrypt_generic
與PKCS5填充(見代碼的打擊),所有的人都可以得到相同的加密爲openssl_encrypt
做了,但還是不一樣的Java函數結果
public static function encrypt($input, $key) {
$key = hash('md5', $key, true);
$iv = '0000000000000000';
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$input = Security::pkcs5_pad($input, $size);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $input, MCRYPT_MODE_CBC, $iv);
// output wd/OTHoIXwgHGDHcj8OTgg==
echo base64_encode($encrypted);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $key, $iv);
$data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = base64_encode($data);
// output wd/OTHoIXwgHGDHcj8OTgg==
echo $data;
}
private static function pkcs5_pad ($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
我有通知,如果我更改加密方法從CBC到歐洲央行的另一種奇怪的東西,Java和PHP的加密功能是一樣的,但可悲的是訪問第三方API,我都用CBC
你如何確保他們有相同的填充? – Rahul
@Rahul我使用PKCS#5 –