我正在尝试解码十六进制字符串并使用aes算法对其进行加密。但是当它在java中通过相同的算法时会给出不同的结果。但是通过hex2bin()传递数据并打印其输出然后将其用作数据会得到正确的结果。为什么?
这是我正在使用的PHP代码片段::
<?php
$data = hex2str("ce4f5bf05a57b6f9e0d7df628d266d66");
//$data = pack('H*', "ce4f5bf05a57b6f9e0d7df628d266d66");
echo "data:".$data." length:".strlen($data).PHP_EOL;
$data2 = "?O[?ZW?????b?&mf";
echo "data2:".$data2." length:".strlen($data2).PHP_EOL;
if (strcmp($data,$data2)) {
echo "Both are equal".PHP_EOL;
} else {
echo "Both are unequal".PHP_EOL;
}
$key = 'mysaltmysalt1234';
$blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'ecb');
$data = pkcs5_pad($data, $blocksize);
$data2 = pkcs5_pad($data2, $blocksize);
echo "type data -- " . gettype($data).PHP_EOL;
echo "type data 2 -- ". gettype($data2).PHP_EOL;
echo "encoding data --" . mb_detect_encoding($data).PHP_EOL;
echo "encoding data 2 -- ". mb_detect_encoding($data2).PHP_EOL;
echo "data:".$data." length:".strlen($data).PHP_EOL;
echo "data2:".$data2." length:".strlen($data2).PHP_EOL;
echo "encrypted data : ".base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB)).PHP_EOL;
echo "encrypted data2 : ".base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data2, MCRYPT_MODE_ECB)).PHP_EOL;
die;
function pkcs5_pad($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
function hex2str($hex) {
$str = '';
for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
return $str;
}
输出 - &gt;
data:?O[?ZW?????b?&mf length:16
data2:?O[?ZW?????b?&mf length:16
Both are equal
type data -- string
type data 2 -- string
encoding data --UTF-8
encoding data 2 -- UTF-8
data:?O[?ZW?????b?&mf length:32
data2:?O[?ZW?????b?&mf length:32
encrypted data : SWDBVA282EY9qXkpe4vuFz+prMZrefR6nymIB3KQpf0=
encrypted data2 : STICb3fdCrutwEy6cg5/sD+prMZrefR6nymIB3KQpf0=
Java代码 -
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import javax.crypto.Cipher;
import java.util.Base64;
import java.security.MessageDigest;
public class HelloWorld
{
public static void main(String[] args) {
String keyhex,salt,salto,keystr;
salt = "mysaltmysalt1234";
keyhex = "ce4f5bf05a57b6f9e0d7df628d266d66";
byte[] binkey = DatatypeConverter.parseHexBinary(keyhex);
keystr = new String(binkey);
salto = encrypt(salt.getBytes(), keystr);
System.out.println(salto);
}
public static String encrypt(byte[] key,String inputString) {
try
{
SecretKeySpec secretKeySpec = new SecretKeySpec(key,
"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(1, secretKeySpec);
byte[] aBytes = cipher.doFinal(inputString.getBytes());
String base64 = new String(Base64.getEncoder().encode(aBytes));
return base64;
} catch(Exception ex) {
System.out.println("Exception occured in encrypt : "+ex.toString());
}
return null;
}
}
Java代码输出:STICb3fdCrutwEy6cg5 / sD + prMZrefR6nymIB3KQpf0 =