Java实现RSA非对称加密

准备工作

了解非对称加密算法 - RSA

公私钥对的概念

需要用到的jar包

Base64编码

为了解决ASCII中一些字符在IDEA中不可打印的问题,使用Base64编码

1、用于处理 密钥字符串

比如公钥:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLhv3lCBJBUfg2cx4WPhmcK1/MiDJ6lwFlBp7Mngtpy+blrwu1mniRiv9Vu7a8u9zsBU0LM9UDXNKsB/ClEsYE1wwu5zcX5jHiQ0Nj2N8fIuo/J53hNetT3fGbN80T81Jf5DA0KV0J3pi7on9lOEZrOyFFZvb2SxapMWyWPGUdHwIDAQAB

其实代表的是一个数字

2、用于处理信息中的中文字符

代码

package RSA;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author WuYongheng
 * @date 2022/11/21
 * @description
 */
public class RsaUtils {

    public static void main(String[] args) throws Exception {
        System.out.println();
        // 生成公私钥对
        RsaKeyPair keyPair = generateKeyPair();
        System.out.println("公钥:" + keyPair.getPublicKey());
        System.out.println("私钥:" + keyPair.getPrivateKey());
        System.out.println();
        test1(keyPair);
        System.out.println("\n");
//        test2(keyPair);
//        System.out.println("\n");
    }

    /**
     * 静态的,跑程序时会优先加载,去调用ReadData()方法
     * 使用 final 关键字,保证读取到的数据不可更改
     */
    private static final String SRC;

    static {
        try {
            SRC = ReadData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用缓存流读取 aaa.txt 文件中的内容
     *
     * @return 文件内容
     * @throws IOException
     */
    public static String ReadData() throws IOException {
        String fileName = "D:\\code\\aaa.txt";
        final StringBuilder myData = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("文件内容是: " + line);
                myData.append(line);
            }
        }
        return myData.toString();
    }

    /**
     * 公钥加密私钥解密
     *
     * @param keyPair
     * @throws Exception
     */
    private static void test1(RsaKeyPair keyPair) throws Exception {
        System.out.println("***************** 公钥加密私钥解密开始 *****************");
        // 用公钥加密得到 text1
        String text1 = encryptByPublicKey(keyPair.getPublicKey(), RsaUtils.SRC);
        // 用私钥解密 text1 得到 text2
        String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1);
        System.out.println("加密前:" + RsaUtils.SRC);
        System.out.println("加密后:" + text1);
        System.out.println("解密后:" + text2);
        if (RsaUtils.SRC.equals(text2)) {
            System.out.println("解密字符串和原始字符串一致,解密成功");
        } else {
            System.out.println("解密字符串和原始字符串不一致,解密失败");
        }
        System.out.println("***************** 公钥加密私钥解密结束 *****************");
    }

    /**
     * 私钥加密公钥解密
     * 过程与 test1类似
     *
     * @param keyPair
     * @throws Exception
     */
    private static void test2(RsaKeyPair keyPair) throws Exception {
        System.out.println("***************** 私钥加密公钥解密开始 *****************");
        String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), RsaUtils.SRC);
        String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);
        System.out.println("加密前:" + RsaUtils.SRC);
        System.out.println("加密后:" + text1);
        System.out.println("解密后:" + text2);
        if (RsaUtils.SRC.equals(text2)) {
            System.out.println("解密字符串和原始字符串一致,解密成功");
        } else {
            System.out.println("解密字符串和原始字符串不一致,解密失败");
        }
        System.out.println("***************** 私钥加密公钥解密结束 *****************");
    }

    /**
     * 公钥加密方法
     *
     * @param publicKeyText 公钥
     * @param text          将要加密的信息
     * @return Base64编码的字符串
     * @throws Exception
     */

    public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
        // 返回按照 X.509 标准进行编码的密钥的字节
        // x509EncodedKeySpec2 是一种规范、规格
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        // 让密钥工厂按照指定的 规范 生成公钥
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        // 对加密初始化,使用加密模式,公钥加密
        // Cipher.ENCRYPT_MODE 可以用 1 代替
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] result = cipher.doFinal(text.getBytes());
        // 返回 Base64编码的字符串
        return Base64.encodeBase64String(result);
    }

    /**
     * 公钥解密方法
     * 过程与encryptByPublicKey()方法类似
     *
     * @param publicKeyText 公钥
     * @param text          待解密的信息
     * @return 字符串
     * @throws Exception
     */

    public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        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.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥加密方法
     * 过程与encryptByPublicKey()方法类似
     *
     * @param privateKeyText 私钥
     * @param text           将要加密的信息
     * @return Base64编码的字符串
     * @throws Exception
     */
    public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
        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.encodeBase64String(result);
    }

    /**
     * 私钥解密方法
     * 过程与encryptByPublicKey()方法类似
     *
     * @param privateKeyText 私钥
     * @param text           待解密的信息
     * @return 字符串
     * @throws Exception
     */

    public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }


    /**
     * 创建RSA公私钥对
     *
     * @return new RsaKeyPair(publicKeyString, privateKeyString)
     * @throws NoSuchAlgorithmException
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        // 创建公私钥对,指定算法 - RSA
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 设置密钥大小 1024 bits, >=512
        keyPairGenerator.initialize(1024);
        // 创建KeyPair对象,用于接收公私钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 生成随机的公私钥对
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 把密钥转换成 Base64编码的字符串
        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
        return new RsaKeyPair(publicKeyString, privateKeyString);
    }


    /**
     * RSA密钥对 对象
     */
    public static class RsaKeyPair {
        private final String publicKey;
        private final String privateKey;

// 也可以将密钥写死
//        private final String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKYZdPEB9UtcTUCn/stBfgi3lu0CuUkQqwKy1tr9vEoeTe5KZqTJ4Fm3GxFChEgdPDUbglUhx0xIhBWu7yEUKy8CAwEAAQ==";
//        private final String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAphl08QH1S1xNQKf+y0F+CLeW7QK5SRCrArLW2v28Sh5N7kpmpMngWbcbEUKESB08NRuCVSHHTEiEFa7vIRQrLwIDAQABAkEAmX+LH7L0kklhpy/ZetMyezHWy3+p5Yj+0QafIlA88qyivvHX2lsAMmHcr5HIVxfWDIZCStU+8sDEfLoVQ6H3uQIhAN0blNwWPBRJ+mFOURsfkPYe5k66ncOTqfKirHovqK3dAiEAwE+fh1F3xuyZWt3YUyDlhf29zl6rYmyO5e3zImxWCnsCIE0CkERfkilW4tgFWQZjZi/y7zA4mz5FLgoOUph0BQIZAiEAo8Ao2pRoJR45xsG3/bC5P8q74AmEbZ56XxaqPNl6uhkCIFiPu1Yc+oFzH0Z5hmxKUlnWqeU/unuZNxcZhbtGY2bd";

        public RsaKeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
//            publicKey = this.publicKey;
//            privateKey = this.privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

    }
}

验证

中文,英文字母,数字,特殊符号

猜你喜欢

转载自blog.csdn.net/Ipkiss_Yongheng/article/details/127963087