java 中使用RSA非对称性加密解密

加密和解密使用不同的密钥(公钥/私钥),非对称加密/解密的安全性是基于复杂数学难题,特点是运算复杂、速度慢,主要应用于金融、军事等重大机密的系统。

使用RSA加密数据时需要使用密钥对,也就是一个公钥,一个私钥。如A、B双方发送数据,A生成密钥对,将公钥发送给B,A将数据用私钥加密后发送给B,而B用A提供的公钥对数据进行解密。如果是B向A发送数据,B用公钥加密数据并发送给A,A使用私钥对数据进行解密。

非常重要的RSAUtils.java完整代码:

package com.example.myfirstkotlin.model;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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;

/**
 * 非对称加密算法RSA
 */
public class RSAUtils {

    /**
     * 指定加密算法为RSA
     */
    private static final String ALGORITHM = "RSA";
    /**
     * 加密填充方式
     */
    public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
    /**
     * 密钥长度,用来初始化
     */
    private static final int KEYSIZE = 1024;
    /**
     * 公钥
     */
    private static Key publicKey = null;
    /**
     * 私钥
     */
    private static Key privateKey = null;
    /**
     * 公钥字符串
     */
    private static String publicKeyString ="";
    /**
     * 私钥字符串
     */
    private static String privateKeyString ="";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 生成密钥对
     *
     * @throws Exception
     */
    public static Map<String, String> generateKeyPair() throws Exception {

//        // /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom secureRandom = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        keyPairGenerator.initialize(KEYSIZE, secureRandom);
//        /** 生成密匙对 */
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        Map<String, String> keyMap = new HashMap<String, String>();
//        /** 得到公钥 */
        BASE64Encoder encoder = new BASE64Encoder();

        keyMap.put("public", new String(encoder.encode(keyPair.getPublic().getEncoded()).getBytes(), "UTF-8"));
        keyMap.put("private", new String(encoder.encode(keyPair.getPrivate().getEncoded()).getBytes(), "UTF-8"));
        return keyMap;
    }

    /**
     * 生成公钥对象
     *
     * @param publicKeyStr
     * @throws Exception
     */
    public static void setPublicKey(String publicKeyStr) throws Exception {
        RSAUtils.publicKey = generatePublicKey(publicKeyStr);
    }

    /**
     * 生成私钥对象
     *
     * @param privateKeyStr
     * @throws Exception
     */
    public static void setPrivateKey(String privateKeyStr) throws Exception {
        RSAUtils.privateKey = generatePrivateKey(privateKeyStr);
    }

    /**
     * 私钥加密方法
     *
     * @param privatekey
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String source, String privatekey) throws Exception {
        generatePrivateKey(privatekey);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] data = source.getBytes();
        /** 执行数据分组加密操作 */
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(encryptedData);
    }

    /**
     * 使用公钥解密算法
     *
     * @param cryptoSrc 密文
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String cryptoSrc, String publicStr) throws Exception {
        setPublicKey(publicStr);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] encryptedData = decoder.decodeBuffer(cryptoSrc);
        /** 执行解密操作 */

        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();

        return new String(decryptedData);
    }


    /**
     * 公钥加密方法
     *
     * @param pubString
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String source, String pubString) throws Exception {
        setPublicKey(pubString);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] data = source.getBytes();
        /** 执行分组加密操作 */
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();

        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(encryptedData);
    }


    /**
     * 私钥解密算法
     *
     * @param cryptoSrc 密文
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String cryptoSrc, String privatekey) throws Exception {
        //生成私钥对象
        setPrivateKey(privatekey);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] encryptedData = decoder.decodeBuffer(cryptoSrc);

        /** 执行解密操作 */
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
    }

    /**
     * 将给定的公钥字符串转换为公钥对象
     *
     * @param publicKeyStr
     * @return
     * @throws Exception
     */
    private static Key generatePublicKey(String publicKeyStr) throws Exception {
        publicKeyString = publicKeyStr;
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (IOException e) {
            throw new Exception("公钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 将给定的私钥字符串转换为私钥对象
     *
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    private static Key generatePrivateKey(String privateKeyStr) throws Exception {
        privateKeyString = privateKeyStr;
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (IOException e) {
            throw new Exception("私钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }



    public static void main(String[] args) throws Exception {

        Map<String, String> keyMap = generateKeyPair();
        System.out.println("public------" + keyMap.get("public"));
        System.out.println("private------" + keyMap.get("private"));
        publicKeyString=keyMap.get("public");
        privateKeyString=keyMap.get("private");
        setPublicKey(publicKeyString);
        setPrivateKey(privateKeyString);
        long a = System.currentTimeMillis();
        System.out.println("公钥字符串: ");
        System.out.println(publicKeyString);
        System.out.println();
        System.out.println();
        System.out.println("公钥字符串长度" + publicKeyString.length());
        System.out.println();
        System.out.println();
        System.out.println("私钥字符串: ");
        System.out.println(privateKeyString);
        System.out.println();
        System.out.println();
        System.out.println("私钥字符串长度" + privateKeyString.length());
        System.out.println();
        System.out.println();
        System.out.println("公钥对象: ");
        System.out.println(publicKey);
        System.out.println();
        System.out.println();
        System.out.println("私钥对象: ");
        System.out.println(privateKey);

        String origin = "高考放榜,有人欣喜,有人失意,无论结果如何,只要奋斗过,就青春无悔。高考能改变人生,但不会决定人生,只要你不停止努力,就可以成为更好的自己。";
        String s = new String(new BASE64Encoder().encodeBuffer(origin.getBytes()));

        String en = encryptByPublicKey(s, publicKeyString);
        System.out.println("en-->" + en);
        String encodedString=new String(new BASE64Decoder().decodeBuffer(decryptByPrivateKey(en, privateKeyString)));
        System.out.println("解密后的字符串====》"+encodedString);

        System.out.println(System.currentTimeMillis() - a);

    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA算法是一种对称加密算法,可以用于对文件进行加密解密。在Java实现RSA算法需要以下步骤: 1. 生成公钥和私钥 首先需要生成RSA算法所需的公钥和私钥。可以使用Java的KeyPairGenerator类来生成。具体代码如下: ```java KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); // 指定密钥长度为2048位 KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); ``` 2. 加密文件 对于要加密的文件,可以使用Java的FileInputStream类来读取文件内容,并将其转换为字节数组。然后使用公钥来对字节数组进行加密。具体代码如下: ```java // 读取文件内容到字节数组 byte[] fileContent = Files.readAllBytes(Paths.get("test.txt")); // 使用公钥进行加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedContent = cipher.doFinal(fileContent); // 将加密后的字节数组写入到文件 Files.write(Paths.get("test.txt.enc"), encryptedContent); ``` 3. 解密文件 对于加密后的文件,可以使用Java的FileInputStream类来读取文件内容,并将其转换为字节数组。然后使用私钥来对字节数组进行解密。具体代码如下: ```java // 读取加密后的文件内容到字节数组 byte[] encryptedContent = Files.readAllBytes(Paths.get("test.txt.enc")); // 使用私钥进行解密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedContent = cipher.doFinal(encryptedContent); // 将解密后的字节数组写入到文件 Files.write(Paths.get("test.txt.dec"), decryptedContent); ``` 需要注意的是,RSA算法一次只能加密一定长度的数据,因此如果要加密的文件比较大,需要将文件分块加密
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值