Kas*_*ain 0 php java encryption
我尝试在 java 6 中使用 OPENSSL_RAW_DATA 执行 PHP openssl_encrypt aes-256-cbc 但没有成功。我找到了一些关于此的主题,但我只成功地在没有 raw_data 的 aes-128-cbc 中做到了这一点。我发现的关于此的最佳主题是:AES-256 CBC 在 php 中加密并在 Java 中解密,反之亦然, 但是 raw_data 不起作用,并且 256 位密钥是随机生成的。事实上 PHP 版本是:
<?php>
openssl(
"hello",
"aes-256-cbc",
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
OPENSSL_RAW_DATA,
"aaaaaaaaaaaaaaaa"
)
?>
Run Code Online (Sandbox Code Playgroud)
我实际上有这个:
public static void main(String[] args) {
try {
// 128 bits key
openssl_encrypt("hello", "bbbbbbbbbbbbbbbb", "aaaaaaaaaaaaaaaa");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
Base64 base64 = new Base64();
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
IvParameterSpec iv = new IvParameterSpec(strIv.getBytes("UTF-8"), 0, ciper.getBlockSize());
// Encrypt
ciper.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encryptedCiperBytes = base64.encode((ciper.doFinal(data.getBytes())));
String s = new String(encryptedCiperBytes);
System.out.println("Ciper : " + s);
return s;
}
Run Code Online (Sandbox Code Playgroud)
经过一些修改和一些测试后我发现了它:
private static String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
Base64 base64 = new Base64();
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(strIv.getBytes(), 0, ciper.getBlockSize());
// Encrypt
ciper.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encryptedCiperBytes = ciper.doFinal(data.getBytes());
String s = new String(encryptedCiperBytes);
System.out.println("Ciper : " + s);
return s;
}
Run Code Online (Sandbox Code Playgroud)
PHP中的openssl_encrypt不会将其结果转换为base64,而且我也使用不带参数的getBytes(),因为对于某些密钥,我有一个关于密钥长度的错误。
所以这个方法做同样的事情:
<?php>
openssl_encrypt(data, "aes-256-cbc", key, OPENSSL_RAW_DATA, iv);
?>
Run Code Online (Sandbox Code Playgroud)