PHP 加密函数
$privateKey = "1234567812345678";
$iv = "1234567812345678";
$data = "Test string";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);
echo(base64_encode($encrypted));
Result: iz1qFlQJfs6Ycp+gcc2z4w==
当我尝试使用下面的函数在 Java 中解密这个结果时,我得到的只是 ì�š@ÔBKxnfÈ~¯Ô'M,而我期待“测试字符串”。我有什么错误的想法吗?谢谢
public static String decrypt() throws Exception{
try{
String Base64EncodedText = "iz1qFlQJfs6Ycp+gcc2z4w==";
String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
String key = "1234567812345678";
String iv = "1234567812345678";
javax.crypto.spec.SecretKeySpec keyspec = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES");
javax.crypto.spec.IvParameterSpec ivspec = new javax.crypto.spec.IvParameterSpec(iv.getBytes());
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] decrypted = cipher.doFinal(decodedText.getBytes());
String str = new String(decrypted);
return str;
}catch(Exception e){
return null;
}
}
编辑:从 Java 8 开始,Java 现在包含一个可接受的 Base64 类,java.util.Base64 https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html.
这条线
String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
看起来不对。相反,使用阿帕奇公共编解码器 http://commons.apache.org/codec/类或更硬的base64 http://iharder.sourceforge.net/current/java/base64/班级。此外,mcrypt 使用的默认填充(零填充)可能是错误的,并且很难在其他语言中使用结果。用户评论部分mcrypt_加密网页 http://www.php.net/manual/en/function.mcrypt-encrypt.php有如何执行此操作的示例。
这是使用 apache commons 类来解密字符串的小示例。
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
public class AESToy3 {
private static final Charset ASCII = Charset.forName("US-ASCII");
public static void main(String[] args) throws Exception {
String base64Cipher = "iz1qFlQJfs6Ycp+gcc2z4w==";
byte [] cipherBytes = Base64.decodeBase64(base64Cipher);
byte [] iv = "1234567812345678".getBytes(ASCII);
byte [] keyBytes = "1234567812345678".getBytes(ASCII);
SecretKey aesKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(cipherBytes);
System.out.println(Hex.encodeHexString(result));
}
}
这会产生以下输出:
5465737420737472696e670000000000
当解码为 ASCII 并删除尾随零时,您可以得到Test string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)