我正在开发一个REST API,其中要传递给服务器的数据需要使用“ AES / CBC / PKCS5Padding”进行加密。 REST API客户端使用Java加密和解密数据,而我使用PHP。
此处使用的秘密密钥是带有sha1的哈希。我与客户端具有相同的密钥值,并且IV值也相同,但是当我尝试加密并将其与客户端进行比较时,它是不同的。
JAVA代码:
import java.util.Arrays;
import java.security.*;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.lang.Object;
class Main {
public static String stringToHex(String base)
{
StringBuffer buffer = new StringBuffer();
int intValue;
for(int x = 0; x < base.length(); x++)
{
int cursor = 0;
intValue = base.charAt(x);
String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
for(int i = 0; i < binaryChar.length(); i++)
{
if(binaryChar.charAt(i) == '1')
{
cursor += 1;
}
}
if((cursor % 2) > 0)
{
intValue += 128;
}
buffer.append(Integer.toHexString(intValue) + " ");
}
return buffer.toString();
}
public static String bytesToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: a)
sb.append(String.format("%02x", b));
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException,
InvalidAlgorithmParameterException,
NoSuchProviderException,
NoSuchPaddingException,
InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException
{
MessageDigest sha = MessageDigest.getInstance("SHA-1");
String secretKey = "mysecretkey102018";
String message = "00155001C"
byte[] key = sha.digest(secretKey.getBytes("UTF-8"));
byte[] value = message.getBytes();
key = Arrays.copyOf(key, 16);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec iv = new IvParameterSpec("AAAAAAAAAAAAAAAA".getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
System.out.println(bytesToHex(cipher.doFinal(value)));
}
PHP代码:
class IDebit
{
private $iv = "AAAAAAAAAAAAAAAA";
private $secret_key = "mysecretkey102018";
private $message = "00155001C";
public function generateEncrytedKeyId()
{
$hashPassword = substr(hash("SHA1", $secret_key), 0, 32);
$blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$str = $this->pkcs5_pad($message, $blocksize);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashPassword, $str, MCRYPT_MODE_CBC, self::IV);
return bin2hex($encrypted);
}
protected function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
}
Java 上的加密结果为c1e7af770d9d0af59cc75d1c76aa78f6
,而 PHP 上的加密结果为d67a15a027be7e7ab68ea6ab88ea4f2f
我想知道我的代码有什么问题。我已经在这个论坛上用Google搜索并检查了数十次,但是无法获得相同的结果。我已经使用该论坛上的人员发布的答案重新检查了我的代码,该代码是相同的。