Java小强个人技术博客站点    手机版
当前位置: 首页 >> 框架 >> Java实现RSA加密示例代码

Java实现RSA加密示例代码

30121 框架 | 2022-6-16

RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。是由一对密钥来进行加解密的过程,分别称为公钥和私钥。公钥加密--私钥解密,私钥加密--公钥解密

rsa.jpg


示例代码

import cn.hutool.core.codec.Base64;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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;

/**
 * RSA加密解密
 **/
@Data
@Service
public class RsaUtils {
    public static void main(String[] args) throws Exception {
        RsaUtils rsaUtils = new RsaUtils();
        RsaKeyPair rsaKeyPair = rsaUtils.generateKeyPair();

        rsaUtils.setPrivateKey(rsaKeyPair.getPrivateKey());
        rsaUtils.setPublicKey(rsaKeyPair.getPublicKey());

        System.out.println("私钥:" + rsaKeyPair.getPrivateKey());
        System.out.println("公钥:" + rsaKeyPair.getPublicKey());

        // 公钥加密,私钥解密
        String rePub = rsaUtils.encryptByPublicKey("duosuna.com");
        System.out.println("公钥 加密后:" + rePub);
        System.out.println("私钥 解密后:" + rsaUtils.decryptByPrivateKey(rePub));

        // 私钥加密,公钥解密
        String rePri = rsaUtils.encryptByPrivateKey("duosuna.com");
        System.out.println("私钥 加密后:" + rePri);
        System.out.println("公钥 解密后:" + rsaUtils.decryptByPublicKey(rePri));
    }

    /**
     * Rsa 私钥
     */
    @Value("${rsa.privateKey}")
    private String privateKey;
    /**
     * Rsa 公钥
     */
    @Value("${rsa.publicKey}")
    private String publicKey;

    /**
     * 私钥加密
     * @param text             待加密的信息
     * @return 加密后的文本
     */
    public String encryptByPrivateKey(String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encode(result);
    }

    /**
     * 私钥解密
     * @param text             待解密的文本
     * @return 解密后的文本
     */
    public String decryptByPrivateKey(String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decode(text));
        return new String(result);
    }

    /**
     * 公钥加密
     * @param text            待加密的文本
     * @return 加密后的文本
     */
    public String encryptByPublicKey(String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decode(publicKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encode(result);
    }

    /**
     * 公钥解密
     * @param text            待解密的信息
     * @return 解密后的文本
     */
    public String decryptByPublicKey(String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decode(publicKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.decode(text));
        return new String(result);
    }

    /**
     * 构建RSA密钥对
     * @return 生成后的公私钥信息
     */
    public RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        String publicKeyString = Base64.encode(rsaPublicKey.getEncoded());
        String privateKeyString = Base64.encode(rsaPrivateKey.getEncoded());
        return new RsaKeyPair(publicKeyString, privateKeyString);
    }

    /**
     * RSA密钥对对象
     */
    @Data
    @AllArgsConstructor
    public class RsaKeyPair {
        private String publicKey;
        private String privateKey;
    }
}


这里密钥对数是按2048进行的,可以修改为其他,也可以使用一些在线工具进行RSA加密解密的测试。


EDN

推荐您阅读更多有关于“ 加密 公钥 RSA 对称 非对称 私钥 ”的文章

上一篇:Elasticsearch Windows上安装 下一篇:Kafka安装Windows版

猜你喜欢

发表评论:

评论:

回复 Java小强 评论于 2022-06-16 10:23
代码示例依赖 https://hutool.cn/docs/#/ 工具包