java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java接口数据加密

Java实现后端和前端的接口数据加密方案详解

作者:咘噜biu

这篇文章主要为大家详细介绍了一种基于椭圆曲线集成加密方案(ECIES)的前后端数据安全交互方法,该方案通过椭圆曲线密码学实现密钥协商,结合AES对称加密保障数据传输安全,感兴趣的小伙伴可以了解下

1.解决问题

前后端在交互过程中,请求和响应的数据需要加密处理,并保证安全和性能。

方案名称:ECIES (Elliptic Curve Integrated Encryption Scheme,椭圆曲线集成加密方案)

2.核心思路

服务端准备

客户端加密(每次请求)

服务端解密

服务端加密:通过3中计算的Key直接加密数据即可

客户端解密:通过2中计算的Key直接解密数据即可

3.代码示例

package com.visy.utils;

import cn.hutool.crypto.symmetric.AES;

import javax.crypto.KeyAgreement;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.function.Consumer;


/**
 * ECIES (Elliptic Curve Integrated Encryption Scheme,椭圆曲线集成加密方案)
 * 这个方案是椭圆曲线密码学中的密码学方案,用于实现前后端间通信的数据加密,是应用内的加密机制。
 * 核心是密钥协商:使用ECDH算法生成密钥对,并计算出共享密钥。
 */
public class ECIESDemo {

    //Base64工具类
    static class BASE64 {
        public static String encode(byte[] data) {
            return Base64.getEncoder().encodeToString(data);
        }

        public static byte[] decode(String base64Str) {
            return Base64.getDecoder().decode(base64Str);
        }
    }

    //ECDH工具
    static class ECDH {
        public static StrKeyPair generateKeyPair(String curveName) throws Exception {
            // 1. 指定椭圆曲线参数,例如 secp256r1 (NIST P-256)
            ECGenParameterSpec ecSpec = new ECGenParameterSpec(curveName);
            // 2. 生成ECC密钥对
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
            kpg.initialize(ecSpec, new SecureRandom());
            KeyPair keyPair = kpg.generateKeyPair();
            return StrKeyPair.of(keyPair);
        }

        /**
         * ECDH核心方法:计算共享秘密
         * @param myPriKey 己方的私钥(Base64字符串)
         * @param otherPubKey 对方的公钥(Base64字符串)
         * @return Base64编码的共享秘密字符串
         */
        public static String deriveSharedSecret(String myPriKey, String otherPubKey) throws Exception {
            PrivateKey myPrivateKey = toPrivateKey(myPriKey);
            PublicKey otherPublicKey = toPublicKey(otherPubKey);

            KeyAgreement ka = KeyAgreement.getInstance("ECDH");
            ka.init(myPrivateKey);
            ka.doPhase(otherPublicKey, true);

            byte[] rawSecret = ka.generateSecret();
            //用SHA-256哈希一次,得到32字节AES-256密钥
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");

            String shearedSecret = BASE64.encode(sha256.digest(rawSecret));
            System.out.println("【共享密钥】计算-私钥:"+myPriKey);
            System.out.println("【共享密钥】计算-公钥:"+otherPubKey);
            System.out.println("【共享密钥】计算-结果:"+shearedSecret);
            System.out.println("---------------------------------");
            return shearedSecret;
        }

        private static PublicKey toPublicKey(String pubKey) throws Exception {
            byte[] decodedBytes = BASE64.decode(pubKey);
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedBytes);
            return keyFactory.generatePublic(keySpec);
        }

        private static PrivateKey toPrivateKey(String priKey) throws Exception {
            byte[] decodedBytes = BASE64.decode(priKey);
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedBytes);
            return keyFactory.generatePrivate(keySpec);
        }
    }

    //AES加解密工具
    static class Aes {
        public static String  encrypt(String data, String key){
            AES aes = new AES(BASE64.decode(key));
            return aes.encryptBase64(data);
        }
        public static String decrypt(String data, String key){
            AES aes = new AES(BASE64.decode(key));
            return aes.decryptStr(BASE64.decode(data));
        }
    }

    //模拟客户端(如浏览器)
    static class Client {
        //服务端公钥,固定值,后续不再更新
        private final String servPubKey;

        public Client(String servPubKey){
            this.servPubKey = servPubKey;
            System.out.println("【客户端】初始化完成,服务端公钥: " + servPubKey);
            System.out.println("---------------------------------");
        }

        public void request(Server server, String message, Consumer<String> callback) throws Exception {
            //生成密钥对
            StrKeyPair keyPair = genKeyPair();
            //计算共享密钥
            String sharedSecret = getSharedSecret(keyPair.getPriKey());
            //对称加密数据
            String reqData = Aes.encrypt(message, sharedSecret);
            //封装传输通道
            Channel channel = new Channel(keyPair.getPubKey(), reqData, resData -> {
                //解密数据
                String data = Aes.decrypt(resData, sharedSecret);
                //将数据传给回调
                callback.accept(data);
            });
            //发送给服务端
            server.receive(channel);
        }

        private StrKeyPair genKeyPair() throws Exception {
            StrKeyPair keyPair = ECDH.generateKeyPair("secp256r1");
            System.out.println("【客户端】公钥: " + keyPair.getPubKey());
            System.out.println("【客户端】私钥: " + keyPair.getPriKey());
            System.out.println("【客户端】已刷新密钥对!");
            System.out.println("---------------------------------");
            return keyPair;
        }

        private String getSharedSecret(String priKey) throws Exception {
            return ECDH.deriveSharedSecret(priKey, this.servPubKey);
        }
    }

    //模拟后台服务端
    static class Server {
        //服务端密钥对,只生成一次
        private final StrKeyPair keyPair;

        public Server() throws Exception {
            this.keyPair = ECDH.generateKeyPair("secp256r1");
            System.out.println("【服务端】公钥: " + this.keyPair.getPubKey());
            System.out.println("【服务端】私钥: " + this.keyPair.getPriKey());
            System.out.println("【服务端】初始化完成!");
            System.out.println("---------------------------------");
        }

        public String getPubKey(){
            return this.keyPair.getPubKey();
        }

        public void receive(Channel channel) throws Exception {
            //客户端公钥
            String clientPubKey = channel.getClientPubKey();
            //计算共享密钥
            //因为服务端私钥是固定的
            //如果客户端不是每次请求都刷新密钥对,可以按clientPubKey直接缓存Key
            //但是要注意内存溢出,可以设置缓存有效时间,指定最大缓存个数等
            String sharedSecret = getSharedSecret(clientPubKey);
            //解密数据
            String message = Aes.decrypt(channel.read(), sharedSecret);
            System.out.println("【服务端】收到消息: " + message);
            System.out.println("【服务端】客户端公钥:" + clientPubKey);
            System.out.println("---------------------------------");

            //响应消息
            String resMsg = "服务端已收到消息->"+ message;
            //加密
            String data = Aes.encrypt(resMsg, sharedSecret);
            //发送
            channel.write(data);
        }

        /**
         * 计算共享密钥(服务端私钥 + 客户端公钥)
         */
        private String getSharedSecret(String clientPubKey) throws Exception {
            return ECDH.deriveSharedSecret(this.keyPair.getPriKey(), clientPubKey);
        }
    }

    //模拟请求通道
    static class Channel {
        private final String reqData;
        private final String clientPubKey;
        private final Consumer<String> callback;

        public Channel(String clientPubKey, String reqData, Consumer<String> callback) {
            this.reqData = reqData;
            this.clientPubKey = clientPubKey;
            this.callback = callback;
        }

        //获取客户端公钥
        public String getClientPubKey(){
            return this.clientPubKey;
        }

        //读取数据
        public String read() {
            return this.reqData;
        }

        //写入数据
        public void write(String resData){
            this.callback.accept(resData);
        }
    }

    //密钥对(base64字符串)
    static class StrKeyPair {
        private final String priKey;
        private final String pubKey;

        private StrKeyPair(KeyPair keyPair) {
            this.priKey = BASE64.encode(keyPair.getPrivate().getEncoded());
            this.pubKey = BASE64.encode(keyPair.getPublic().getEncoded());
        }

        public static StrKeyPair of(KeyPair keyPair) {
            return new StrKeyPair(keyPair);
        }

        public String getPriKey() {
            return this.priKey;
        }

        public String getPubKey() {
            return this.pubKey;
        }
    }

    //测试
    public static void main(String[] args) throws  Exception {
        //创建服务端
        Server server = new Server();
        //创建客户端
        Client client = new Client(server.getPubKey());

        //向服务端发送请求
        client.request(server, "hello world", data -> {
            System.out.println("【客户端】收到消息: " + data);
        });
        System.out.println("============================================");
        //向服务端发送请求
        client.request(server, "{\"name\": \"张三\"}", data -> {
            System.out.println("【客户端】收到消息: " + data);
        });
        System.out.println("============================================");
    }
}

4.输出

【服务端】公钥: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUutqZsAN1Kh+FFvS95lKFob0zKZZY0mtBKNOYFSZ/WzaLO8CHH1zjcH3nV82MxXwyj0t+yhP/Dugfriy8VIWbg==
【服务端】私钥: MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCAaJ/UnsK4Tt+1Vyt9vyAnYqinr8uobgPZOlvCMeihKkg==
【服务端】初始化完成!
---------------------------------
【客户端】初始化完成,服务端公钥: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUutqZsAN1Kh+FFvS95lKFob0zKZZY0mtBKNOYFSZ/WzaLO8CHH1zjcH3nV82MxXwyj0t+yhP/Dugfriy8VIWbg==
---------------------------------
【客户端】公钥: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDz5YRdfRm1l0Wj0BqIBMEq2zLca96eidX/DEIZipQol8gzV4YKiLwtWxmS2rplAay1/4stiuofvLFZZAJ0rM/w==
【客户端】私钥: MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCDLGtJ2Lxm+8cd+o1iDbxkigojjFdy+9k/wVhQ0XJTRQw==
【客户端】已刷新密钥对!
---------------------------------
【共享密钥】计算-私钥:MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCDLGtJ2Lxm+8cd+o1iDbxkigojjFdy+9k/wVhQ0XJTRQw==
【共享密钥】计算-公钥:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUutqZsAN1Kh+FFvS95lKFob0zKZZY0mtBKNOYFSZ/WzaLO8CHH1zjcH3nV82MxXwyj0t+yhP/Dugfriy8VIWbg==
【共享密钥】计算-结果:fIPyLCxiu26stP2C4bGyCU8Eh+uYUWp3w8PjRWdxh8k=
---------------------------------
【共享密钥】计算-私钥:MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCAaJ/UnsK4Tt+1Vyt9vyAnYqinr8uobgPZOlvCMeihKkg==
【共享密钥】计算-公钥:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDz5YRdfRm1l0Wj0BqIBMEq2zLca96eidX/DEIZipQol8gzV4YKiLwtWxmS2rplAay1/4stiuofvLFZZAJ0rM/w==
【共享密钥】计算-结果:fIPyLCxiu26stP2C4bGyCU8Eh+uYUWp3w8PjRWdxh8k=
---------------------------------
【服务端】收到消息: hello world
【服务端】客户端公钥:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDz5YRdfRm1l0Wj0BqIBMEq2zLca96eidX/DEIZipQol8gzV4YKiLwtWxmS2rplAay1/4stiuofvLFZZAJ0rM/w==
---------------------------------
【客户端】收到消息: 服务端已收到消息->hello world
============================================
【客户端】公钥: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGbyRS8JTE32TLAMXYaFpi8pY8Cf2R7u9gdta+PnB7thgyAZ5FEBGjgRhNEL2MFD7g5B8yLX3cTghpjisajs4Tw==
【客户端】私钥: MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCADaXXP8AmBXXhrDJIXpFBH9byFr+ak38DAY1J1+zCktQ==
【客户端】已刷新密钥对!
---------------------------------
【共享密钥】计算-私钥:MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCADaXXP8AmBXXhrDJIXpFBH9byFr+ak38DAY1J1+zCktQ==
【共享密钥】计算-公钥:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUutqZsAN1Kh+FFvS95lKFob0zKZZY0mtBKNOYFSZ/WzaLO8CHH1zjcH3nV82MxXwyj0t+yhP/Dugfriy8VIWbg==
【共享密钥】计算-结果:7ngHo0nz8W2Zv9vMKORu5jC7uPIhgsZaS/657vCpcUs=
---------------------------------
【共享密钥】计算-私钥:MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCAaJ/UnsK4Tt+1Vyt9vyAnYqinr8uobgPZOlvCMeihKkg==
【共享密钥】计算-公钥:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGbyRS8JTE32TLAMXYaFpi8pY8Cf2R7u9gdta+PnB7thgyAZ5FEBGjgRhNEL2MFD7g5B8yLX3cTghpjisajs4Tw==
【共享密钥】计算-结果:7ngHo0nz8W2Zv9vMKORu5jC7uPIhgsZaS/657vCpcUs=
---------------------------------
【服务端】收到消息: {"name": "张三"}
【服务端】客户端公钥:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGbyRS8JTE32TLAMXYaFpi8pY8Cf2R7u9gdta+PnB7thgyAZ5FEBGjgRhNEL2MFD7g5B8yLX3cTghpjisajs4Tw==
---------------------------------
【客户端】收到消息: 服务端已收到消息->{"name": "张三"}
============================================

5.落地建议

服务端的加解密数据操作应该添加全局处理,比如拦截器,AOP切面等。

客户端的加解密数据操作同样应该全局处理,比如 axios的拦截器内。

全局处理加解密数据可以让编写业务的人不用关心加解密,使用起来是无感的(就像不加解密之前一样)

前后端应该协商好传输的格式,比如:

POST提交,JSON格式:

{
	"key": "客户端公钥",
	"data": "加密数据"
}

GET提交:url?key=客户端公钥&data=加密数据

6.结合前端完整示例

本示例中为了和前端js插件统一,所有密钥均用十六进制(hex)表示,不再用Base64的形式

6.1后端代码

package com.visy.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import javax.crypto.KeyAgreement;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.*;
import java.util.Arrays;
import java.util.Base64;

/**
 * Hex 十六进制版本的ECDH工具
 */
public class HexECDHDemo {
    static class Hex {
        /**
         * BigInteger转64字符hex(补零)
         */
        private static String to64Hex(BigInteger num) {
            String hex = num.toString(16);
            if (hex.length() < 64) {
                return repeatedStr('0', 64 - hex.length()) + hex;
            }
            return hex;
        }

        private static String bytesToHex(byte[] bytes) {
            return HexUtil.encodeHexStr(bytes);
        }

        public static byte[] hexToBytes(String hex){
            return HexUtil.decodeHex(hex);
        }

        private static String repeatedStr(char ch, int count) {
            if (count <= 0) {
                return "";
            }
            char[] chars = new char[count];
            Arrays.fill(chars, ch);
            return new String(chars);
        }
    }

    public static class StrKeyPair {
        private final String priKey;
        private final String pubKey;

        private StrKeyPair(String priKey, String pubKey) {
            this.priKey = priKey;
            this.pubKey = pubKey;
        }

        public static StrKeyPair of(KeyPair keyPair) {
            // 1. 提取公钥坐标
            ECPublicKey ecPubKey = (ECPublicKey) keyPair.getPublic();
            ECPoint point = ecPubKey.getW(); //返回椭圆曲线上的点 (x, y坐标)

            // 2. 格式化为04+x+y格式
            BigInteger x = point.getAffineX(), y = point.getAffineY();
            String xHex = Hex.to64Hex(x), yHex = Hex.to64Hex(y);
            String publicKey = "04" + xHex + yHex;

            // 3. 提取私钥原始值
            ECPrivateKey ecPriKey = (ECPrivateKey) keyPair.getPrivate();
            String privateKey = Hex.to64Hex(ecPriKey.getS()); //返回私钥的标量值(大整数)

            return new StrKeyPair(privateKey, publicKey);
        }

        public String getPriKey() {
            return this.priKey;
        }

        public String getPubKey() {
            return this.pubKey;
        }
    }

    public static class ECDH {
        private static final String CURVE_NAME = "secp256r1";
        /**
         * 生成密钥对(返回hex格式)
         */
        public static StrKeyPair genKeyPair() throws Exception {
            // 1. 生成标准密钥对
            ECGenParameterSpec ecSpec = new ECGenParameterSpec(CURVE_NAME);
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
            kpg.initialize(ecSpec, new SecureRandom());
            KeyPair keyPair = kpg.generateKeyPair();

            //转换成Hex字符串的密钥对
            return StrKeyPair.of(keyPair);
        }

        public static String derive(String myPriKey, String otherPubKey) throws Exception {
            PrivateKey myPrivateKey = toPrivateKey(myPriKey);
            PublicKey otherPublicKey = toPublicKey(otherPubKey);

            // 3. 执行ECDH
            KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
            keyAgreement.init(myPrivateKey);
            keyAgreement.doPhase(otherPublicKey, true);

            // 4. 获取共享密钥(原始字节)
            byte[] sharedSecret = keyAgreement.generateSecret();

            // 5. 返回hex
            return Hex.bytesToHex(sharedSecret);
        }

        /**
         * 将04+x+y格式的hex公钥转换为Java PublicKey
         */
        private static PublicKey toPublicKey(String pubKey) throws Exception {
            if (!pubKey.startsWith("04")) {
                throw new IllegalArgumentException("公钥必须以04开头");
            }else if(pubKey.length() !=  130){
                throw new IllegalArgumentException("公钥格式有误");
            }

            // 提取x, y坐标
            String xHex = pubKey.substring(2, 66), yHex = pubKey.substring(66, 130);
            BigInteger x = new BigInteger(xHex, 16), y = new BigInteger(yHex, 16);

            // 获取曲线参数
            ECParameterSpec ecParams = getECParameterSpec();

            // 创建EC点
            ECPoint point = new ECPoint(x, y);

            // 创建公钥规范
            ECPublicKeySpec keySpec = new ECPublicKeySpec(point, ecParams);
            KeyFactory keyFactory = KeyFactory.getInstance("EC");

            return keyFactory.generatePublic(keySpec);
        }

        /**
         * 将hex私钥转换为Java PrivateKey
         */
        private static PrivateKey toPrivateKey(String priKey) throws Exception {
            BigInteger s = new BigInteger(priKey, 16);

            // 获取曲线参数
            ECParameterSpec ecParams = getECParameterSpec();

            // 创建私钥规范
            ECPrivateKeySpec keySpec = new ECPrivateKeySpec(s, ecParams);
            KeyFactory keyFactory = KeyFactory.getInstance("EC");

            return keyFactory.generatePrivate(keySpec);
        }

        /**
         * 获取椭圆曲线参数
         */
        private static ECParameterSpec getECParameterSpec() throws Exception {
            // 通过生成临时密钥对获取曲线参数
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
            kpg.initialize(new ECGenParameterSpec(CURVE_NAME));
            KeyPair tempKeyPair = kpg.generateKeyPair();

            return ((ECPublicKey) tempKeyPair.getPublic()).getParams();
        }
    }

    //Base64工具类
    static class BASE64 {
        public static String encode(byte[] data) {
            return Base64.getEncoder().encodeToString(data);
        }

        public static byte[] decode(String base64Str) {
            return Base64.getDecoder().decode(base64Str);
        }
    }

    //AES加解密工具
    static class Aes {
        public static String  encrypt(String data, String key, String iv){
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, Hex.hexToBytes(key), Hex.hexToBytes(iv));
            return aes.encryptBase64(data);
        }
        public static String decrypt(String data, String key, String iv){
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, Hex.hexToBytes(key), Hex.hexToBytes(iv));
            return aes.decryptStr(BASE64.decode(data));
        }
    }

    public static void main(String[] args) throws Exception {
        // 生成密钥对,只生成一次,将公钥和前端共享
        //StrKeyPair strKeyPair = ECDH.genKeyPair();
        //04122670c45aa251ecef1528f76c248e288cd35dd728538764cbdaf3efa1c91bccc184daec61cc9abd660f947a530da82e3b4a76a07271d0d96a92660592722d39
        //System.out.println("服务端公钥:" + strKeyPair.getPubKey());
        //9353c717bb2d65b5516e0e6c56fa7574592767d8abe70e796c1719e8f9d4d55b
        //System.out.println("服务端私钥:" + strKeyPair.getPriKey());

        //服务端私钥(需保密)
        String servPrivateKey = "9353c717bb2d65b5516e0e6c56fa7574592767d8abe70e796c1719e8f9d4d55b";
        //客户端公钥,来自前端请求参数
        String clientPublicKey = "04dd42dadd5d99539c15410aede7943a9c55ecb175d687feac37a602293e8a90fc76daa2d1d0186147628cb8ca24e86e7710b5e024e5a0d7ff55d0b342cf4f2d6e";
        //计算共享秘密(Aes 加密密钥)
        String secret = ECDH.derive(servPrivateKey, clientPublicKey);
        System.out.println("共享秘密:"+ secret);

        //来自前端的向量iv和加密后的数据
        String iv = "34f5653b77a3b85db7826a40768d12a3";
        String encryptData = "pBkwIDR15BWS7xk2R5YPVmnXasrQpyybTq+C1N8/XTU=";

        //解密并输出结果
        System.out.println("解密结果:"+Aes.decrypt(encryptData, secret, iv));
    }
}

6.2 前端代码

<!doctype html>
<html>
  <head >
	<title>ECDH Test</title>
  </head>
  <body >
	  <div style="text-align: center">
		<div style = "margin-top:200px;display:flex;flex-direction: column;align-items: center;gap: 10px;">
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">服务端公钥: </div>
			<textarea rows="3" cols="80" id="serv_pub_key_ipt" style="font-size: 20px"></textarea>
			<button id="compute" style="margin-left:20px">生成并计算共享密钥</button>
		  </div>
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">本地公钥: </div>
			<textarea rows="3" cols="80" id="pub_key_ipt" style="font-size: 20px"></textarea>
		  </div>
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">本地私钥: </div>
			<textarea rows="3" cols="80" id="pri_key_ipt" style="font-size: 20px"></textarea>
		  </div>
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">共享秘密: </div>
			<textarea rows="3" cols="80" id="sheared_key_ipt" style="font-size: 20px; font-weight:bold"></textarea>
		  </div>
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">发送内容: </div>
			<textarea rows="3" cols="80" id="data_ipt" style="font-size: 20px"></textarea>
			<button id="do_encrypt" style="margin-left:20px">加密</button>
		  </div>
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">IV: </div>
			<textarea rows="1" cols="80" id="iv_ipt" style="font-size: 20px; font-weight:bold"></textarea>
		  </div>
		  <div style="width: 800px;display:flex;flex-direction: row">
			<div style="width:150px;text-align:right;margin-right:10px">加密结果: </div>
			<textarea rows="3" cols="80" id="encrypt_data_ipt" style="font-size: 20px; font-weight:bold"></textarea>
		  </div>
		</div>
	  </div>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
	<!-- ecdh用到的插件,生成密钥对,计算共享秘密 -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/elliptic/6.6.1/elliptic.min.js"></script>
	<!-- 数据加密插件,需用到AES -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js"></script>
	<script>
		(function(){
			const EC = elliptic.ec;
			const ec = new EC('p256'); // 选择椭圆曲线secp256k1的别名是p256
			//生成共享秘密
			$("#compute").on("click", function (){
			  const servPubKey = $("#serv_pub_key_ipt").val();
				if(servPubKey==null || !(servPubKey+"").trim()){
					alert("请先输入服务端公钥!");
					return;
				}
				const keyPair = ec.genKeyPair(); //生成密钥对
				const priKey = keyPair.getPrivate("hex");
				const pubKey = keyPair.getPublic("hex");
				$("#pub_key_ipt").val(pubKey);
				$("#pri_key_ipt").val(priKey);
				const secret = derive(priKey, servPubKey);
				$("#sheared_key_ipt").val(secret);
			})
			//加密
			$("#do_encrypt").on("click", function(){
				const data = $("#data_ipt").val();
				if(data==null || !(data+"").trim()){
					alert("请先输入发送内容!");
					return;
				}
				const secret = $("#sheared_key_ipt").val();
				if(secret==null || !(secret+"").trim()){
					alert("请先生成共享秘密!");
					return;
				}
			    const iv = generateIV();
				$("#iv_ipt").val(iv);
			    const encryptData = aesEncrypt(data, secret, iv);
				$("#encrypt_data_ipt").val(encryptData);
			})
			// 2. 使用对方公钥和自己的私钥生成共享密钥
			function derive(myPriKey, otherPubKey) {
			  try {
				// 从十六进制字符串加载自己的私钥
				const myPrivateKey = ec.keyFromPrivate(myPriKey, 'hex');
				// 从十六进制字符串加载对方的公钥
				const otherPublicKey = ec.keyFromPublic(otherPubKey, 'hex').getPublic();
				// 计算共享密钥
				const sharedSecret = myPrivateKey.derive(otherPublicKey);
				return sharedSecret.toString(16);
			  } catch (error) {
				console.error('生成共享密钥失败:', error);
				return null;
			  }
			}
			/**
			 * AES加密函数
			 * @param {string} plaintext - 明文
			 * @param {string} keyHex - 密钥(64字符hex,对应32字节)
			 * @param {string} ivHex - 初始向量(32字符hex,对应16字节)
			 * @returns {string} Base64格式的加密结果
			 */
			function aesEncrypt(plaintext, keyHex, ivHex) {
				// 将hex字符串转换为CryptoJS格式
				var key = CryptoJS.enc.Hex.parse(keyHex);
				var iv = CryptoJS.enc.Hex.parse(ivHex);
				// 执行AES-256-CBC加密
				var encrypted = CryptoJS.AES.encrypt(plaintext, key, {
					iv: iv,
					mode: CryptoJS.mode.CBC,
					padding: CryptoJS.pad.Pkcs7
				});
				// 返回Base64字符串
				return encrypted.toString();
			}
			/**
			 * AES解密函数
			 * @param {string} ciphertextBase64 - Base64格式的密文
			 * @param {string} keyHex - 密钥(64字符hex)
			 * @param {string} ivHex - 初始向量(32字符hex)
			 * @returns {string} 解密后的明文
			 */
			function aesDecrypt(ciphertextBase64, keyHex, ivHex) {
				// 将hex字符串转换为CryptoJS格式
				var key = CryptoJS.enc.Hex.parse(keyHex);
				var iv = CryptoJS.enc.Hex.parse(ivHex);
				// 执行AES-256-CBC解密
				var decrypted = CryptoJS.AES.decrypt(ciphertextBase64, key, {
					iv: iv,
					mode: CryptoJS.mode.CBC,
					padding: CryptoJS.pad.Pkcs7
				});
				// 转换为UTF-8字符串
				return decrypted.toString(CryptoJS.enc.Utf8);
			}
			/**
			 * 生成随机IV(16字节)
			 * @returns {string} 32字符的hex IV
			 */
			function generateIV() {
				// 生成16字节随机数
				var randomBytes = CryptoJS.lib.WordArray.random(16);
				// 转换为hex字符串
				return randomBytes.toString(CryptoJS.enc.Hex);
			}
		})();
	</script>
  </body>
</html>

前端页面

前端传参

{
	"clientPublicKey": "04dd42dadd5d99539c15410aede7943a9c55ecb175d687feac37a602293e8a90fc76daa2d1d0186147628cb8ca24e86e7710b5e024e5a0d7ff55d0b342cf4f2d6e",
	"iv": "34f5653b77a3b85db7826a40768d12a3",
	"encryptData": "pBkwIDR15BWS7xk2R5YPVmnXasrQpyybTq+C1N8/XTU="
}

后端输出

后端需接收前端的本地公钥 + IV + 加密结果,然后计算出共享秘密,解密数据

共享秘密:f2e5a1b995524d818c9b6c5076e5bcace40641a6244f91dfe72b560f3723fc3d
解密结果:{"name":"张三","age":25}

到此这篇关于Java实现后端和前端的接口数据加密方案详解的文章就介绍到这了,更多相关Java接口数据加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文