后端接口在提交过程中,我们系统一般都是明文传输的,因为恰巧接口参数没有做签名,所以就导致了数据篡改的分风险,因为没太多时间做数据签名,所以就打算用RSA 的方式直接对入参做加密,然后后端解密处理,但是由于RSA 对比较大的参数无法做加密,所以就采用了融合加密的方式处理了。

具体逻辑就是先对入参数据做AES加密。密钥随机生成,然后再将随机生成的密钥用RSA加密,然后将使用AES加密的数据,以及使用RSA加密的key 传输到后端,后端通过RSA解密密钥,再利用AES解密正常的数据,实现双重加密传输,以下为部分代码。

@Data
public class SubmitParams {
    /**
    AES 加密数据
    */
    private String data;
    /**
    通过RSA 加密的AES 密钥
    */
    private String key;
}

``

public SubmitInfoReqParams decryptcacheString(SubmitParams params) {
​
    // 使用提供的私钥进行解密
    SubmitInfoReqParams requestVo = null;
    try {
        String privateKeyString = "-----BEGIN PRIVATE KEY-----\n" +
                "-----END PRIVATE KEY-----\n";
        PrivateKey privateKey = RSAUtil.getPrivateKeyFromPEM(privateKeyString); // 加载你的RSA私钥
        String decryptKey = RSAUtil.decrypt(params.getKey(),privateKey);
        log.info("解密后的key :"+ decryptKey);
​
        // 利用解密后的key对jsonString进行解密
        String decryptJsonString = EncryptAndDecodeUtil.decrypt(params.getData(),decryptKey);
        log.info("解密后的jsonString :"+ decryptJsonString);
        // 将解密后的JSON字符串转换为BaseRequest<OpenInfoReqParams>
        ObjectMapper objectMapper = new ObjectMapper();
        requestVo = objectMapper.readValue(decryptJsonString, new TypeReference<SubmitInfoReqParams>() {
        });
    } catch (Exception e) {
        log.error("解密异常:{}", e.getMessage());
    }
    return requestVo;
}
​
​
/**
RSAUtil.decrypt 方法
*/
public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
 }

可以在加密的接口中使用decryptcacheString 方法进行数据的解密,同时也能写个拦截器,拦截所有接口统一的解密逻辑