栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java-RSA非对称加密算法实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java-RSA非对称加密算法实现

java RSA 非对称加密算法实现

1、新建 RsaUtil 工具类

package com.comm.utils;

import com.alibaba.fastjson.JSON;
import com.comm.entity.po.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import static java.lang.System.out;


@Slf4j
public class RsaUtil {

    
    public static final String KEY_ALGORITHM = "RSA";

    public static final String RSA_PUBLIC_KEY = "rsaPublicKey";
    public static final String RSA_PRIVATE_KEY = "rsaPrivateKey";
    
    public static final String RSA_ENCRYPTION_RESULT = "encryptionResult";
    
    public static final Integer INIT_KEY_SIZE = 1024;

    
    private static final Map KEY_MAP = new HashMap<>();


    
    public static void initRsaKey() throws Exception{
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(INIT_KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        log.info("公钥信息生成:publicKey");
        log.info("私钥信息生成:privateKey");
        KEY_MAP.put(RSA_PUBLIC_KEY,rsaPublicKey);
        KEY_MAP.put(RSA_PRIVATE_KEY,rsaPrivateKey);
    }

    
    public static String encryptionByPublicKey(String data){
        try {
            //初始化key
            initRsaKey();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) KEY_MAP.get(RSA_PUBLIC_KEY);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] res = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            KEY_MAP.put(RSA_ENCRYPTION_RESULT,res);
            return Base64.encodeBase64String(res);
        }catch (Exception e){
            log.error("数据加密失败:{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    
    public static String decryptByPrivate(){
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            RSAPrivateKey privateKey = (RSAPrivateKey) KEY_MAP.get(RSA_PRIVATE_KEY);
            byte[] res = (byte[]) KEY_MAP.get(RSA_ENCRYPTION_RESULT);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            res = cipher.doFinal(res);
            return new String(res);
        }catch (Exception e){
            log.error("数据解密失败:{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    //方法二|私钥加密、公钥解密
    private static void jdkRsa(String data) {
        try {
            // 初始化密钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGenerator.initialize(INIT_KEY_SIZE);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            log.info("公钥信息生成:publicKey");
            log.info("私钥信息生成:privateKey");

            // 私钥加密,公钥解密 -- 加密
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

            // 私钥加密,公钥解密 -- 解密
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            result = cipher.doFinal(result);
            out.println("私钥加密,公钥解密 -- 解密"+new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2、具体实现调用

//加密  返回一个加密串
String pwd = RsaUtil.encryptionByPublicKey(加密数据);
//解密后的数据
String data = RsaUtil.decryptByPrivate();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020366.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号