场景:
app开发,对接接口,进行签名sign验证,采用aes加密,最后发现php中生成的sign与java(android)中不一样,尝试了一阵子找到解决方法:
php中aes加解密:
<?php
$str='www.hu-rong.com';
$key='d8b2b7da008e57bd4f4f7b3177415973';
$iv='1234567890123456';//此种模式下iv长度为16
$method='aes-256-cbc';
echo '要加密的字符串:'.$str.'<br/>';
echo 'key:'.$key.'<br/>';
echo 'iv:'.$iv.'<br/>';
echo '模式:'.$method.'<br/>';
echo '加密后的结果是:<br/>';
echo $str_jiami=openssl_encrypt($str, $method, $key, 0, $iv);
echo '<br/>解密后的结果是:';
echo openssl_decrypt($str_jiami, $method,$key,false,$iv);
运行结果:
key:d8b2b7da008e57bd4f4f7b3177415973
iv:1234567890123456
模式:aes-256-cbc
加密后的结果是:
vJOK/SYa068JScpaOrTfeg==
解密后的结果是:www.hu-rong.com
要加密的字符串:www.hu-rong.com
java中加密方法1,遗憾的是这个没有提供解密方法:
https://blog.csdn.net/xiojing825/article/details/78491374
package main.java.com.leon.channel.command;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String data = "my_data";
String passwrod = "my_password";
String iv = "1234567890123456";
try {
String base64Str = java_openssl_encrypt(data, passwrod, iv);
//输出: uD1WB/3VZH+zEObhVxdQvA==
System.out.print(base64Str);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String java_openssl_encrypt(String data, String password, String iv) throws Exception {
byte[] key = new byte[32];
for (int i = 0; i < 32; i++) {
if (i < password.getBytes().length) {
key[i] = password.getBytes()[i];
} else {
key[i] = 0;
}
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
new IvParameterSpec(iv.getBytes()));
String base64Str = Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
return base64Str;
}
}
java aes加解密方法2:
https://github.com/simplephp/php-java-AES-128-ECB/blob/master/aes.php
此种方法的php代码比较古老,php7.2中报错:
Call to undefined function mcrypt_get_block_size
此时要安装mcrypt扩展:
https://blog.csdn.net/yhb598712254/article/details/80621473
http://pecl.php.net/package/mcrypt/1.0.1
wget http://pecl.php.net/get/mcrypt-1.0.1.tgz
tar zxvf mcrypt-1.1.1.tgz
cd mcrypt-1.0.1
phpize
./configure
make && make install
修改php.ini
重启php-fpm
如果安装mcrypt报错:
编译报错:configure: error: mcrypt.h not found. Please reinstall libmcrypt.
执行:
yum install -y epel-release
yum install -y libmcrypt-devel
两个不能一起安装,因为CentOs6默认的yum源没有 libmcrypt-devel这个包,只能借助epel的yum源,所以先安装epel,再安装libmcrypt。
最后能跑但还是会给出提示,因mcrypt比较古老,已弃用;