以前,我有一个工作系统来加密PHP中的数据并使用JAVA解密它。这是PHP代码:
function encrypt($message, $initialVector, $secretKey) {
return base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
md5($secretKey),
$message,
MCRYPT_MODE_CFB,
$initialVector
)
);
}
function decrypt($message, $initialVector, $secretKey) {
$decoded = base64_decode($message);
return mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
md5($secretKey),
$decoded,
MCRYPT_MODE_CFB,
$initialVector
);
}
和java代码
public String decrypt(String encryptedData, String initialVectorString, String secretKey) {
String decryptedData = null;
try {
SecretKeySpec skeySpec = new SecretKeySpec(md5(secretKey).getBytes(), "AES");
IvParameterSpec initialVector = new IvParameterSpec(initialVectorString.getBytes());
Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, initialVector);
byte[] encryptedByteArray = (new org.apache.commons.codec.binary.Base64()).decode(encryptedData.getBytes());
byte[] decryptedByteArray = cipher.doFinal(encryptedByteArray);
decryptedData = new String(decryptedByteArray, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return decryptedData;
}
但是,我最近从PHP 5.x切换到7.1,现在收到以下消息:
"函数mcrypt_encrypt()已弃用"
所以似乎mcrypt不再是一个很好的选择。我搜索了很多,但大多数例子仍然使用mcrypt。唯一的其他好的选择是指像RNCryptor这样的工具或者是化解的,但是没有任何工作实例。是否有一些适用于PHP和JAVA的简单工作示例?我需要能够将数据解密为其原始形式,因为我需要使用它执行某些任务。
提前致谢
答案 0 :(得分:2)
这看起来像这个链接的代码:http://php.net/manual/de/function.mcrypt-encrypt.php#119395。但无论如何,我认为它应该被openssl_encrypt()取代。
这是你的功能的一个端口(当然没有md5)。
<?php
function encrypt_new($data, $iv, $key, $method)
{
return base64_encode(openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv));
}
function decrypt_new($data, $iv, $key, $method)
{
return openssl_decrypt(base64_decode($data), $method, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
}
$data = "plain text";
$method = 'AES-128-CFB8'; // AES/CFB8/NoPadding
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$password = 'default-secret-salt';
$key = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$encrypted = encrypt_new($data, $iv, $key, $method);
echo $encrypted. "\n";
$decrypted = decrypt_new($encrypted, $iv, $key, $method);
echo $decrypted. "\n"; // plain text
答案 1 :(得分:0)
您是否考虑过从mcrypt_encrypt
转移到openssl_encrypt
。请记住,openssl
在给定相同的明文和密钥时不会输出相同的密码。
此外,最好删除md5
因为它非常快速且容易暴力。