我有问题转换PHP代码与解密成java的例子。 这是php代码:
function decrypt($encrypted, $password, $salt='2#g+XK^Sc3"4ABXbvwF8CPD%en%;9,c(') {
// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
$key = hash('SHA256', $salt . $password, true);
// Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
$iv = base64_decode(substr($encrypted, 0, 22) . '==');
// Remove $iv from $encrypted.
$encrypted = substr($encrypted, 22);
// Decrypt the data. rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
// Retrieve $hash which is the last 32 characters of $decrypted.
$hash = substr($decrypted, -32);
// Remove the last 32 characters from $decrypted.
$decrypted = substr($decrypted, 0, -32);
// Integrity check. If this fails, either the data is corrupted, or the password/salt was incorrect.
if (md5($decrypted) != $hash) return false;
// Yay!
return $decrypted;
}
这是我的java代码,我做了什么。但这不起作用。
private static String password = "AxkbK2jZ5PMaeNZWfn8XRLUWF2waGwH2EkAXxBDU6aZ";
private static String salt = "2#g+XK^Sc3\"4ABXbvwF8CPD%en%;9,c(";
private static String text = "Fm+Zfufqe3DjRQtWcYdw9g9oXriDjrAkRrBLhEfu7fCtT4BzD0gw7D+8KxrcbbgJm26peTUWHU2k4YJ4KqCSRQN3NPzuXwlJ4mC4444Edg3Q==";
public String decrypt(String pass, String encr) {
try {
int i = 0;
String key = hash();
byte[] iv = Base64.decodeBase64(text.substring(0, 22) + "==");
Cipher cipher = Cipher.getInstance("DES");
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "DES");
IvParameterSpec ivSpec = new IvParameterSpec(salt.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
ByteArrayInputStream fis = new ByteArrayInputStream(iv);
CipherInputStream cis = new CipherInputStream(fis, cipher);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
// decrypting
byte[] b = new byte[8];
while ((i = cis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
cis.close();
fis.close();
return fos.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String hash() {
StringBuffer sb = new StringBuffer();
try {
MessageDigest md = null;
md = MessageDigest.getInstance("SHA-256");
md.update((password + salt).getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
return sb.toString();
}
}
答案 0 :(得分:2)
您的代码存在一些问题。
MCRYPT_RIJNDAEL_128
是AES而不是DES。这是两种完全不同的算法。Cipher.getInstance("DES");
可能默认为Cipher.getInstance("DES/ECB/PKCS5Padding");
,具体取决于您的默认JCE提供程序
Cipher.getInstance("AES/CBC/NoPadding");
并自行删除尾部0x00和0x04字节。key
,而是直接使用非密钥的密码。此外,您的密钥不应该是十六进制编码,因为您还在PHP中使用原始密钥。在原始PHP代码中有些令人畏惧的事情: