• RSA加密的使用(前后端)


    公钥(publicKey)加密、私钥(privateKey)解密。不能逆向,私钥(privateKey)加密、公钥(publicKey)解密。说白了就是前后端都需要用公钥(publicKey)进行加密,用私钥(privateKey)进行解密。

    引入前端 JS 库:jsencrypt.js

    npm install jsencrypt 
    
    • 1

    使用

    后端生成RSAUtil工具类

    public class RSAUtil {
    	static {
    		Security.addProvider(new BouncyCastleProvider());
    	}
    	    /**
         * 随机生成密钥对
         *
         * @param filePath 密钥对要存储的路径
         */
        public static void genKeyPair(String filePath) {
    		// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    		KeyPairGenerator keyPairGen = null;
    		try {
    			keyPairGen = KeyPairGenerator.getInstance("RSA");
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		// 初始化密钥对生成器,密钥大小为96-1024位
    		keyPairGen.initialize(1024, new SecureRandom());
    		// 生成一个密钥对,保存在keyPair中
    		KeyPair keyPair = keyPairGen.generateKeyPair();
    		// 得到私钥
    		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    		// 得到公钥
    		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    		try {
    			// 得到公钥字符串
    			String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
    			// 得到私钥字符串
    			String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
    			// 将密钥对写入到文件
    			FileWriter pubfw = new FileWriter(filePath + "/publicKey.key");
    			FileWriter prifw = new FileWriter(filePath + "/privateKey.key");
    			BufferedWriter pubbw = new BufferedWriter(pubfw);
    			BufferedWriter pribw = new BufferedWriter(prifw);
    			pubbw.write(publicKeyString);
    			pribw.write(privateKeyString);
    			pubbw.flush();
    			pubbw.close();
    			pubfw.close();
    			pribw.flush();
    			pribw.close();
    			prifw.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
        /**
         * 去除密钥的多余信息
         *
         * @param key 公钥或私钥字符串
         * @return Base64的密钥 base 64 key
         */
        public static String getBase64Key(String key) {
    		key = key.replaceAll("-----BEGIN (.*)-----", "");
    		key = key.replaceAll("-----END (.*)----", "");
    		key = key.replaceAll("\r\n", "");
    		key = key.replaceAll("\n", "");
    		return key;
    	}
        /**
         * 从文件中加载密钥
         *
         * @param fileName 公钥或私钥的文件名
         * @return 字符串形式的密钥 ,去除-----BEGIN (.*)-----等多余信息
         */
        public static String loadKeyFromFile(String fileName) {
    		byte[] keyBytes = loadRawKeyFromFile(fileName);
    
    		// convert to der format
    		return getBase64Key(new String(keyBytes));
    	}
    
        /**
         * 从文件中加载密钥
         *
         * @param fileName 公钥或私钥的文件名
         * @return 字符串形式的密钥 byte [ ]
         */
        public static byte[] loadRawKeyFromFile(String fileName) {
    		InputStream resourceAsStream = RSAUtil.class.getClassLoader().getResourceAsStream(fileName);
    		DataInputStream dis = new DataInputStream(resourceAsStream);
    		byte[] keyBytes = null;
    		try {
    			keyBytes = new byte[resourceAsStream.available()];
    			dis.readFully(keyBytes);
    			dis.close();
    		} catch (IOException e) {
    			throw new SystemException("Failed to load public key from file '" + fileName + "'", e);
    		}
    		return keyBytes;
    	}
    
        /**
         * Load private key by str rsa private key.
         * 加载秘钥
         * @param privateKeyStr the private key str
         * @return the rsa private key
         */
        public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) {
    		try {
    			byte[] buffer = Base64.getDecoder().decode(privateKeyStr);
    			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
    			KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); // KeyFactory.getInstance("RSA");
    			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    		} catch (NoSuchAlgorithmException e) {
    			throw new SystemException("无此算法", e);
    		} catch (InvalidKeySpecException e) {
    			throw new SystemException("私钥非法", e);
    		} catch (NullPointerException e) {
    			throw new SystemException("私钥数据为空", e);
    		} catch (NoSuchProviderException e) {
    			throw new SystemException("no such provider: RSA, BC", e);
    		}
    	}
    
     /**
         * 公钥加密过程
         *
         * @param publicKey     公钥
         * @param plainTextData 明文数据
         * @return 密文 byte [ ]
         */
        public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) {
    		if (publicKey == null) {
    			throw new SystemException("加密公钥为空");
    		}
    		Cipher cipher = null;
    		try {
    			// 使用默认RSA
    			cipher = Cipher.getInstance("RSA");
    			// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
    			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    			byte[] output = cipher.doFinal(plainTextData);
    			return output;
    		} catch (NoSuchAlgorithmException e) {
    			throw new SystemException("无此加密算法", e);
    		} catch (NoSuchPaddingException e) {
    			throw new SystemException("无此加密算法", e);
    		} catch (InvalidKeyException e) {
    			throw new SystemException("加密公钥非法,请检查", e);
    		} catch (IllegalBlockSizeException e) {
    			throw new SystemException("明文长度非法", e);
    		} catch (BadPaddingException e) {
    			throw new SystemException("明文数据已损坏", e);
    		}
    	}
    
        /**
         * 私钥加密过程
         *
         * @param privateKey    私钥
         * @param plainTextData 明文数据
         * @return 密文 byte [ ]
         * @throws Exception 加密过程中的异常信息
         */
        public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
    		if (privateKey == null) {
    			throw new SystemException("加密私钥为空");
    		}
    		Cipher cipher = null;
    		try {
    			// 使用默认RSA
    			cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");// Cipher.getInstance("RSA");
    			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    			byte[] output = cipher.doFinal(plainTextData);
    			return output;
    		} catch (NoSuchAlgorithmException e) {
    			throw new SystemException("无此加密算法", e);
    		} catch (NoSuchPaddingException e) {
    			throw new SystemException("系统中无此填充机制", e);
    		} catch (InvalidKeyException e) {
    			throw new SystemException("加密私钥非法,请检查", e);
    		} catch (IllegalBlockSizeException e) {
    			throw new SystemException("明文长度非法", e);
    		} catch (BadPaddingException e) {
    			throw new SystemException("明文数据已损坏", e);
    		}
    	}
    
        /**
         * 私钥解密过程
         *
         * @param privateKey 私钥
         * @param cipherData 密文数据
         * @return 明文 byte [ ]
         */
        public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) {
    		if (privateKey == null) {
    			throw new SystemException("解密私钥为空");
    		}
    		Cipher cipher = null;
    		try {
    			// 使用默认RSA
    			cipher = Cipher.getInstance("RSA");
    			// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
    			cipher.init(Cipher.DECRYPT_MODE, privateKey);
    			byte[] output = cipher.doFinal(cipherData);
    			return output;
    		} catch (NoSuchAlgorithmException e) {
    			throw new SystemException("无此解密算法", e);
    		} catch (NoSuchPaddingException e) {
    			throw new SystemException("系统中无此填充机制", e);
    		} catch (InvalidKeyException e) {
    			throw new SystemException("解密私钥非法", e);
    		} catch (IllegalBlockSizeException e) {
    			throw new SystemException("密文长度非法");
    		} catch (BadPaddingException e) {
    			throw new SystemException("密文数据已损坏", e);
    		}
    	}
    
        /**
         * 公钥解密过程
         *
         * @param publicKey  公钥
         * @param cipherData 密文数据
         * @return 明文 byte [ ]
         * @throws Exception 解密过程中的异常信息
         */
        public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
    		if (publicKey == null) {
    			throw new SystemException("解密公钥为空");
    		}
    		Cipher cipher = null;
    		try {
    			// 使用默认RSA
    			cipher = Cipher.getInstance("RSA");
    			// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
    			cipher.init(Cipher.DECRYPT_MODE, publicKey);
    			byte[] output = cipher.doFinal(cipherData);
    			return output;
    		} catch (NoSuchAlgorithmException e) {
    			throw new SystemException("无此解密算法", e);
    		} catch (NoSuchPaddingException e) {
    			throw new SystemException("系统中无此填充机制", e);
    		} catch (InvalidKeyException e) {
    			throw new SystemException("解密公钥非法", e);
    		} catch (IllegalBlockSizeException e) {
    			throw new SystemException("密文长度非法");
    		} catch (BadPaddingException e) {
    			throw new SystemException("密文数据已损坏");
    		}
    	}
    
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248

    前端加密

    const JSEncrypt = window.JSEncrypt;
    
    export function rsa(str) {
      const jse = new JSEncrypt();
      const { publicKey } = xxx;//从后端接口获取publicKey
      jse.setPublicKey(publicKey);
      return jse.encrypt(str)
    }
    
    
    export default function(str) {
      return rsa(str)
    }
    
    export const decrypt = async str => {
      return new Promise((resolve, reject) => {
        后端解密接口(str)
          .then(res => {
            if (res.data.code === "success") {
              resolve(res.data.data);
            } else {
              reject(res);
            }
          })
          .catch(err => {
            reject(err)
          });
      })
    }
    
    
    
    
    • 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

    后端解密接口

    //eg: 后端获取publicKey接口
    @GetMapping("getRsaPublicKey")
    public ResultResp getRsaPublicKey() {
        String key = RSAUtil.loadKeyFromFile("rsaPublicKey.key");
        return success(key);
    }
    
    //eg:后端解密接口
    @GetMapping("getDecryptRsaPwd")
    public Result getDecryptRsaPwd(String rsaPwd) {
        //对传进来的字符串做处理,把空格更改成“+”号
        String s = rsaPwd.replaceAll(" +", "+");
        String privateKeyStr = RSAUtil.loadKeyFromFile("rsaPrivateKey.key");
         // rsa解密
         byte[] cipherData = Base64.getDecoder().decode(rsaPwd);
         byte[] xpwd = RSAUtil.decrypt(RSAUtil.loadPrivateKeyByStr(privateKey), cipherData);
         String  decryptRsaPwd = new String(xpwd);
        return Result.success(decryptRsaPwd);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    使用

    import encrypt, { decrypt } from '@/utils/xxx;//引入上面写的前端前端文件
    //加密密码
    data.password = encrypt(data.password); 
    //解密
    decrypt(this.password).then(clearText => {
      this.model.password = clearText
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    HTML标签全解
    组播技术→
    git 使用之撤销暂存区提交
    基于JAVA师生交流平台计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    基于 Keras 的图像分类器
    L40.linux命令每日一练 -- 第七章 Linux用户管理及用户信息查询命令 -- useradd和usermod
    Linux学习——目录操作和库使用
    2021 XV6 4:traps
    [NCTF2019]True XML cookbook
    PyQt 信号与槽之多窗口数据传递(Python)
  • 原文地址:https://blog.csdn.net/qq_43586088/article/details/134312750