有人能告诉我如何解密用这个PHP函数加密的数据(使用Java)吗?
public function pad($data, $blocksize = 16) {
$pad = $blocksize - (strlen($data) % $blocksize);
return $data . str_repeat(chr($pad), $pad);
}
public function decryptECB($data) {
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::BLOB_ENCRYPTION_KEY, self::pad($data), MCRYPT_MODE_ECB);
}
public function encryptECB($data) {
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::BLOB_ENCRYPTION_KEY, self::pad($data), MCRYPT_MODE_ECB);
}
我在这里尝试了大部分内容,但大多数都没有填充,即使我添加填充它们也不起作用。
编辑1:
(来自PHP)
输入如下所示:http://pastebin.com/2cyig9nh
关键是:
M02cnQ51Ji97vwT4
输出为:http://pastebin.com/XcA50UGH
(Java代码)
public class Mcrypt {
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "M02cnQ51Ji97vwT4";
public Mcrypt() {
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public String encrypt(String text) throws Exception {
if (text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec );
encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return Base64.encodeBase64String(encrypted);
}
public byte[] decrypt(String code) throws Exception {
if (code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec );
decrypted = cipher.doFinal(new Base64().decode(code.getBytes()));
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
private static String padString(String source) {
char paddingChar = ' ';
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
return source;
}
}
答案 0 :(得分:3)
您正在Java代码中对Base64进行编码和解码,但您的PHP代码似乎无法执行任何编码/解码。这似乎可以通过您在Pastebin上发布的内容得到证实。如果你想使用字符串而不是字节 - 字节是现代密码接受的唯一输入 - 那么你应该确保双方的(字符)编码是正确的。如果你只想使用字节,不要用Java解码二进制文件 - 输入已经是字节,而不是文本。