接口加密传输设计及AES加解密代码DEMO
接口加密的方案设计:可以将请求的json字符串aes加密,通过params字段传输, 接口服务端接收到参数,先解密,然后转换成对象。 继续业务逻辑的处理。 (另外一种方案是:针对敏感字段aes加密,服务接收端对敏感字段来解密处理)
RequestVo对象:
代码语言:javascript复制 private String params;
private String sign;
伪代码
代码语言:javascript复制String encrypt = requestVo.getParams();
RealReqVO realReqVO = new RealReqVO();
String decryptJson = decryt(encrypt,key);
//json转换为对象
realReqVO = JSON.parseObject(decryptJson,ReceiveReqVO.class);
log.info("数据接口(解密后),入参:{}", JSON.toJSONString(realReqVO));
if(StringUtils.isBlank(realReqVO.getSign())){
realReqVO.setSign(request.getSign());
}
//对sign简单处理是:能否aes解密成功~
validateSign(request.getSign(), key);
以下是AES加解密的DEMO
代码语言:javascript复制import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
public class DesTest {
public static String decryt(String input, String key) {
byte[] output = null;
String res = "";
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
output = cipher.doFinal(Base64.decodeBase64(input.getBytes()));
return new String(output,StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String encrypt(String input, String key) {
String res = "";
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
byte[] output = cipher.doFinal(input.getBytes());
res = Base64.encodeBase64String(output);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
public static void main(String[] args) throws Exception {
//Input length must be multiple of 16 when decrypting with padded cipher
//AES解密报错,Input length must be multiple of 16 when decrypting with padded cipher
//加密方案及AES加密,需要同一个key。 或者是AES密文被修改,无法解密。
//AES解密报错,Input length must be multiple of 16 when decrypting with padded cipher
//具体解决就是:在解密前再转一次编码,基本就能解决这一报错问题。
//原因分析:前端enCode在后端解析失败,最后的=无法解析,导致偏移向量对应不上,报错
//String un="8RKHWcE11foCm2+aEuFG6w==";
//String pd="TQafftXrh8aXYNFJcPgw1w==";
//先转编码!!!
//String ufUserName = URLDecoder.decode(un, "UTF-8");
//String ufPassWord = URLDecoder.decode(pd, "UTF-8");
//此时里面的= 解析成了=
//8RKHWcE11foCm2+aEuFG6w==
//TQafftXrh8aXYNFJcPgw1w==
//然后再去解密
//Invalid AES key length: 7 bytes
String key = "testKeytestKeytestKeytestKey1234"; //32位长度
String content = "{10086}";
String encrypt = encrypt(content, key);
System.out.println("encrypt=" encrypt);
String decrypt = decryt(encrypt, key);
System.out.println("decrypt=" decrypt);
}
}