【发布时间】:2014-07-30 22:08:06
【问题描述】:
我正在使用 AES,我想选择一个密钥,我可以在 Java 端使用它来加密字符串,我在 php 端对相同的密钥进行硬编码,如果字符串匹配,我会解密字符串我通过身份验证进入.
以下是我的 Java 代码:
public class AESencrp {
private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
这是我在 PHP 中使用的函数:
function fnDecrypt()
{
// echo $_POST['key'];
$sValue = $_POST['key'];
$sSecretKey = "TheBestSecretKey";
return rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
$sSecretKey,
base64_decode($sValue),
MCRYPT_MODE_CBC,
mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_256,
MCRYPT_MODE_CBC
),
MCRYPT_RAND
)
), "\0"
);
}
但是,我似乎总是在 php 端得到不同的解密文本,我觉得问题出在密钥上,而由于我正在对其进行硬编码,所以这种行为不应该发生,有什么提示吗?
【问题讨论】:
-
MCRYPT_RIJNDAEL_256不是 AES。试试MCRYPT_RIJNDAEL_128。 -
好的,让我试试。这是否意味着我也必须考虑 128 位密钥?或者我可以使用 256 键?