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;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/7/19
 * String publicKey = Base64.encodeBase64String(rsaPublicKey.getEncoded());
 * String privateKey = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
 * 私钥加密,公钥解密 -- 加密 : Base64.encodeBase64String(result)
 * 私钥加密,公钥解密 -- 解密 : new String(result)
 **/
@Slf4j
public class RsaUtil {

    /**
     * 指定加密算法 使用RSA算法,非对称加密
     */
    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;

    /**
     * key
     * 保存公钥、私钥、以及公钥加密结果
     */
    private static final Map<String,Object> KEY_MAP = new HashMap<>();


    /**
     * 初始化key
     * @throws Exception e
     */
    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);
    }

    /**
     * 公钥加密
     * @param data 数据
     * @return string
     */
    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;
    }

    /**
     * 私钥解密
     * @return string
     */
    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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个简单的RSA非对称密码算法的Java实现,代码如下: ```java import java.math.BigInteger; import java.security.SecureRandom; public class RSA { private BigInteger privateKey; private BigInteger publicKey; private BigInteger modulus; private int bitLength = 1024; private SecureRandom random; // 构造函数 public RSA() { random = new SecureRandom(); BigInteger p = BigInteger.probablePrime(bitLength, random); BigInteger q = BigInteger.probablePrime(bitLength, random); BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); modulus = p.multiply(q); publicKey = BigInteger.probablePrime(bitLength / 2, random); while (phi.gcd(publicKey).compareTo(BigInteger.ONE) > 0 && publicKey.compareTo(phi) < 0) { publicKey.add(BigInteger.ONE); } privateKey = publicKey.modInverse(phi); } // 获取私钥 public BigInteger getPrivateKey() { return privateKey; } // 获取公钥 public BigInteger getPublicKey() { return publicKey; } // 获取模数 public BigInteger getModulus() { return modulus; } // 加密 public byte[] encrypt(byte[] message) { return (new BigInteger(message)).modPow(publicKey, modulus).toByteArray(); } // 解密 public byte[] decrypt(byte[] message) { return (new BigInteger(message)).modPow(privateKey, modulus).toByteArray(); } } ``` 使用该RSA类进行加密和解密的示例代码如下: ```java public static void main(String[] args) { RSA rsa = new RSA(); // 明文 String message = "Hello, world!"; // 加密 byte[] encryptedMessage = rsa.encrypt(message.getBytes()); // 解密 byte[] decryptedMessage = rsa.decrypt(encryptedMessage); System.out.println("明文: " + message); System.out.println("加密后的密文: " + new String(encryptedMessage)); System.out.println("解密后的明文: " + new String(decryptedMessage)); } ``` 注意:该实现只是一个简单的示例,实际使用中需要加入更多的安全措施,比如添加数字签名等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值