近日项目对接,php对接java接口实现数据的请求。其中由于两种语言的语法及函数用法不同,调试起来比较挠头,网上参考了很多关于加密的文章
php中关于AES加密对应Java中的SHA1PRNG方式加密的实例详 此案例所用的php5的函数居多,对于项目长久来说不利;
php7 aes 对接java aes SHA1PRNG算法 本文主要参考此微博
废话不多说直接上代码,java代码如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83package com.hcmdonline.util.security;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
public static final String DEFAULT_ENCODE = "UTF-8";
/**
* <p>加密,编码UTF-8</p>
* @param data 待加密数据
* @param secretKey 秘钥
* @return 加密数据
*/
public static String encrypt(String data, String secretKey){
String strs = null;
try {
byte[] bytes = doAES(Cipher.ENCRYPT_MODE, data.getBytes(), secretKey.getBytes());
// base64编码字节
strs = new String(Base64.getEncoder().encode(bytes), DEFAULT_ENCODE);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return strs;
}
/**
* <p>解密,编码UTF-8</p>
* @param data 待解密数据
* @param secretKey 秘钥
* @return 解密数据
*/
public static String decrypt(String data, String secretKey){
String strs = null;
try {
byte[] src = Base64.getDecoder().decode(data);
byte[] bytes = doAES(Cipher.DECRYPT_MODE, src, secretKey.getBytes());
strs = new String(bytes, DEFAULT_ENCODE);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return strs;
}
public static byte[] doAES(int mode, byte[] data, byte[] key){
try{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key);
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat,"AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(mode, keySpec);// 初始化
return cipher.doFinal(data);
}catch (Exception e){
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String secretKey = "123456";
String data = "{\"鹅宿池边树\":\"僧踹月下门\"}";
String encryptData = encrypt(data, secretKey);
System.out.println("明文是: " + data);
System.out.println("加密后: " + encryptData);
System.out.println("解密后:" + decrypt(encryptData, secretKey));
}
}
php 代码如下
1 |
|