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;
        }

    }
}

验证

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

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值