RSA加密实现

应用场景:

        因项目维护过程中会涉及到等保测评,测评结果显示登录口令没有做加密传输,因此要求使用符合国家使用要求的加密算法,比如RSA或者SM3,本文选择使用RSA做加密处理。

        算法的原理这里就不再做说明,网上可以找到更专业的解释,我这边就是简单的理解为使用工具生成一对公钥(可以提供给前端使用,不怕暴露)和私钥(需要保密,不能暴露(公钥和私钥可使用后端代码生成,下边有后端代码示例),前端使用公钥加密后进行传输,后端接收到加密串之后使用私钥进行解密后验证口令是否正确。

        下边是使用过程:

一、前端:

        前端使用之前需要先引入jsencrypt插件,我们会调用里面的一些方法:

如果使用<script>标签方式引入js需要先下载js文件放到项目中使用

jsencrypt.min.js下载地址:https://www.bootcdn.cn/jsencrypt/

引入示例:

<script type="text/javascript" src="${contextPath}/resources/js/util/jsencrypt.min.js"></script>

vue引入示例:

import { encrypt } from '@/util/jsencrypt'

调用demo:

var PUBLIC_KEY = '你的公钥内容......';
// 加密
function encryptPwd(txt) {
   var encryptor = new JSEncrypt();
   encryptor.setPublicKey(PUBLIC_KEY); 
   return encryptor.encrypt(txt);
}
//加密调用结果:
var username = encryptPwd($('#userName').val());
var password = encryptPwd($('#password').val());

二、后端

后端直接上代码(作为工具类供调用):

package com.aaa.bbb.ccc.util;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA非对称加解密实现
 * (使用公钥加密,使用私钥解密)
 */
public class RSAEncrypt {

    /**
     * 公钥与私钥组
     */
    private static Map<String, Object> keyMap = new HashMap<>();

    /**
     * 随机生成密钥对(公钥+私钥)
     */
    public static String genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        String strPublicKey = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
        // 将公钥和私钥保存到Map
        keyMap.put(strPublicKey,privateKey);
        return strPublicKey;
    }

    /**
     * RSA公钥加密
     *
     * @param str 加密字符串
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encode = Base64.getEncoder().encode(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        return new String(encode);
    }

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @param privateKey 私钥
     * @return 明文
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    public static void main(String[] args) throws Exception {

        //生成公钥和私钥
        genKeyPair();
        //加密字符串
        String message = "123qwe!@#";
        String strPublicKey = genKeyPair();
        System.out.println("随机生成的公钥为:" + strPublicKey);

        Object privatePair = keyMap.get(strPublicKey);
        RSAPrivateKey privateKey = (RSAPrivateKey) privatePair;
        String strPrivateKey = new String(Base64.getEncoder().encode((privateKey.getEncoded())));

        System.out.println("随机生成的私钥为:" + strPrivateKey);
        String messageEn = encrypt(message,strPublicKey);

        System.out.println(message + "加密后的字符串为:" + messageEn);
        String messageDe = decrypt(messageEn,strPrivateKey);
        System.out.println("解密后的字符串为:" + messageDe);

    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值