敏感数据加密传输

1.前端SM4加密

20240828122836

  • 从sessionStorage中获取key和iv加密手机号

    src\views\Home.vue

1
2
3
4
5
6
this.homeForm.phoneNumber = this.tempPhomeNumber
SM4Data.key = sessionStorage.getItem("secretKey")
SM4Data.iv = sessionStorage.getItem("iv")
SM4Data.originalData = this.homeForm.phoneNumber
encryptSM4(SM4Data)
this.homeForm.phoneNumber = SM4Data.encryptedData
  • 发送给密文到后端

    src\views\Home.vue

1
this.axios.get('/getApiTest', { params: this.homeForm })

image-20231230134106728

2.后端读取SM4密钥

  • 后端j接口处获取到加密后的请求数据

com/gaomu/controller/HelloController.java

1
2
3
4
5
6
7
@Autowired
private DataTestService dataTestService;

@RequestMapping("/getApiTest")
public ResponseResult getApiTest(@RequestParam String nickName, @RequestParam String phoneNumber){
return dataTestService.getApiTest(nickName, phoneNumber);
}
  • 获取到loginUser中的密钥数据

    com/gaomu/server/impl/DataTestServiceImpl.java

1
2
3
4
5
6
7
//从loginUser中获取用户密钥等数据
UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
String nickName1 = loginUser.getUser().getNickName();
String phoneNumber1 = loginUser.getUser().getPhoneNumber();
String secretKey = loginUser.getUser().getSecretKey();
String iv = loginUser.getUser().getIv();

3.解密密文

  • 使用密钥解密数据

com/gaomu/server/impl/DataTestServiceImpl.java

1
phoneNumber = SM4Util.decryptCBC(phoneNumber, secretKey, iv);

4.加密响应数据

  • 使用密钥加密邮件,并将密文返回前端

    com/gaomu/server/impl/DataTestServiceImpl.java

1
2
3
4
5
6
7
if (Objects.equals(nickName1, nickName) && Objects.equals(phoneNumber1, phoneNumber)) {
String email = loginUser.getUser().getEmail();
String cipherEmail = SM4Util.encryptCBC(email, secretKey, iv);
Map<String, String > map = new HashMap<>();
map.put("email", cipherEmail);
return new ResponseResult(200, "获取邮件成功", map);
}

image-20231230134212122

5.前端解密密文

  • 前端在回调函数中解密返回的密文数据

    src\views\Home.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
this.axios.get('/getApiTest', { params: this.homeForm }).then((resp) =>{
let data = resp.data;
if(data.code==200){
SM4Data.encryptedData = data.data.email
decryptSM4(SM4Data)
this.email = SM4Data.decryptedData
this.$message({
message: data.msg,
type:'success'
});
} else{
this.$message({
message: data.msg,
type:'error'
});
}

至此双向数据加密传输完成