RSA生成公私钥对springsecurity认证前的前台加密数据加解密

生成公私钥及加解密工具类

package com.xxx.xxx.util;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Java RSA 加密工具类
 * 参考: https://blog.csdn.net/qy20115549/article/details/83105736
 */
public class RSAUtils {
    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 1111111111;//请选择适合自己的长度
    /**
     * 用于封装随机产生的公钥与私钥
     */
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();

    /**
     * 随机生成密钥对
     */
    public static Map<Integer, String> genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        // 将公钥和私钥保存到Map
        //0表示公钥
        keyMap.put(0, publicKeyString);
        //1表示私钥
        keyMap.put(1, privateKeyString);
        return keyMap;
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    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);
        String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str);
        //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 {
        long temp = System.currentTimeMillis();
        //生成公钥和私钥
        genKeyPair();
        //加密字符串
        System.out.println("公钥:" + keyMap.get(0));
        System.out.println("私钥:" + keyMap.get(1));
        System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");


        String message = "RSA测试ABCD~!@#$";
        System.out.println("原文:" + message);

        temp = System.currentTimeMillis();
        String messageEn = encrypt(message, keyMap.get(0));
        System.out.println("密文:" + messageEn);
        System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");

        temp = System.currentTimeMillis();

        String messageDe = decrypt(messageEn, keyMap.get(1));
        System.out.println("解密:" + messageDe);
        System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
    }
}

前端发起请求获取公钥

@GetMapping ( "/encrypt/publickey")
    public String getPublicKey() throws IOException {

        Map<Integer,String> redisKeyPairs = (Map<Integer, String>) JSONObject.parse((String) redisTemplate.opsForValue().get("keypairs"));

        if(redisKeyPairs == null){
            try{
                Map<Integer, String> keyPairs = RSAUtils.genKeyPair();

                redisTemplate.opsForValue().set("keypairs", JSONObject.toJSONString(keyPairs),30, TimeUnit.MINUTES);
                return keyPairs.get(0);
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("异常!");
            }
        }else{
            return redisKeyPairs.get(0);
        }
    }
//注:生成的公私钥为了解密需要,这里采用存储在redis库中,存取时间为30分钟
//注:获取公钥接口需在springsecurity配置类WebSecurityConfig的protected void configure(HttpSecurity httpSecurity) 方法中放行
package com.xxx.xxx.config;


import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.auth.util.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.chinatechstar.auth.service.impl.AuthServiceImpl;

import java.util.Collection;
import java.util.Map;

/**
 * Web安全配置类
 * springSecurity安全管理框架配置类继承WebSecurityConfigurerAdapter
 * @版权所有 广州恒星科创信息技术有限公司
 *
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private AuthServiceImpl authServiceImpl;
	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 为特定的Http请求配置基于Web的安全约束
	 */
	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		//授权相关
		//httpSecurity.authorizeRequests().anyRequest().authenticated().and().csrf().disable();
		httpSecurity.authorizeRequests().antMatchers("/encrypt/publickey").permitAll()
				//.antMatchers("/oauth/token").permitAll()
				.antMatchers("/users/getSysUser").permitAll()
				.and()
				.authorizeRequests()
				.anyRequest().authenticated()
				.and()
				.csrf().disable();
		httpSecurity.headers().cacheControl();
	}

	/**
	 * 配置认证信息
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {

		authenticationManagerBuilder.authenticationProvider(authProvider()).userDetailsService(authServiceImpl).passwordEncoder(new BCryptPasswordEncoder());
		//authenticationManagerBuilder.userDetailsService(authServiceImpl).passwordEncoder(new BCryptPasswordEncoder());
	}

	/**
	 * 实例化AuthenticationManager对象,以处理认证请求
	 */
	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}


	@Bean
    public MyAuthProvider authProvider(){
		return new MyAuthProvider();
	}

/*		    @Bean
    public MyAuthFailHandler authFailHandler(){
		return new MyAuthFailHandler();
	}*/

}

对前端加密后的密码进行解密

//为截取前端传过来的数据,需自己写authProvider并实现AuthenticationProvider接口,并对密码进行解密
package com.xxx.auth.config;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.auth.service.impl.AuthServiceImpl;
import com.chinatechstar.auth.util.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.Principal;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author :chaogry
 * @date :Created in 2020/7/22 13:52
 * @description:用户登录认证配置类
 * @modified By:
 * @version: $
 */
@Configuration
public class MyAuthProvider implements AuthenticationProvider {
    @Autowired
    private AuthServiceImpl authServiceImpl;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        redisTemplate.opsForValue().get("keypairs");
        Map<Integer,String> keypairs = (Map<Integer, String>) JSONObject.parse((String) redisTemplate.opsForValue().get("keypairs"));
        String privateKey = keypairs.get(1);
        String password = null;
        String username = authentication.getName();
        try{
            password = RSAUtils.decrypt((String) authentication.getCredentials(), privateKey);
        } catch (Exception e){
            e.printStackTrace();
        }
        String finalPassword = password;

        Authentication authentication1 = new Authentication() {
            @Override
            public boolean equals(Object another) {
                return false;
            }

            @Override
            public String toString() {
                return authentication.toString();
            }

            @Override
            public int hashCode() {
                return authentication.hashCode();
            }

            @Override
            public String getName() {
                return username;
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                return authentication.getAuthorities();
            }

            @Override
            public Object getCredentials() {
                return finalPassword;
            }

            @Override
            public Object getDetails() {
                return authentication.getDetails();
            }

            @Override
            public Object getPrincipal() {
                return authentication.getPrincipal();
            }

            @Override
            public boolean isAuthenticated() {
                return authentication.isAuthenticated();
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

            }
        };

        UserDetails userDetails = authServiceImpl.loadUserByUsername(authentication1.getName());

        String pwd = (String) authentication1.getCredentials();
        if(userDetails == null){
            throw new AuthenticationCredentialsNotFoundException("authError");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(bCryptPasswordEncoder.matches(pwd,userDetails.getPassword())){
            return new UsernamePasswordAuthenticationToken(userDetails,null,authentication1.getAuthorities());
        }else{
            throw new BadCredentialsException("authError");
        }


    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}



//将自己的provider注入进WebSecurityConfig
	@Bean
    public MyAuthProvider authProvider(){
		return new MyAuthProvider();
	}
//配置认证信息中配置使用自己的provider
	@Override
	protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {

		authenticationManagerBuilder.authenticationProvider(authProvider()).userDetailsService(authServiceImpl).passwordEncoder(new BCryptPasswordEncoder());
		
	}

前台用公钥加密的省略
----完

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-七秒钟记忆

微薄打赏,小编的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值