欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

非对称加密算法之Java RSA算法应用 附可用工具类

程序员文章站 2024-03-14 14:33:34
...

欢迎大家关注本博,同时欢迎大家评论交流,可以给个赞哦!!!

  RSA算法简介

  RSA公开**密码*是一种使用不同的加***与解***,“由已知加***推导出解***在计算上是不可行的”密码*。

  在公开**密码*中,加***(即公开**)PK是公开信息,而解***(即秘***)SK是需要保密的。加密算法E和解密算法D也都是公开的。虽然解***SK是由公开**PK决定的,但却不能根据PK计算出SK。

  RSA允许你选择公钥的大小。512位的**被视为不安全的;768位的**不用担心受到除了国家安全管理(NSA)外的其他事物的危害;1024位的**几乎是安全的。

  关于RSA概念性的内容不做过多介绍,大家可以自行百度。

  Maven 依赖

  工具类对于加密后使用Base64进行编码,所以需要依赖Apache Commons Codec。

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

  工具类实现

  RSAUtil提供了针对文本内容、字节数组内容的加解密实现,RSAUtil工具类可以直接复制使用,代码如下:

package com.arhorchin.securitit.enordecryption.rsa;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

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

/**
 * @author Securitit.
 * @note RSA加密算法实现.
 */
public class RSAUtil {

    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(RSAUtil.class);

    /**
     * 数据编码.
     */
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * 加密算法RSA.
     */
    public static final String RSA_NAME = "RSA";

    /**
     * 获取公钥的key.
     */
    public static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key.
     */
    public static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小.
     */
    public static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小.
     */
    public static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * RSA**长度必须是64的倍数,在512~65536之间。默认是1024.
     */
    public static final int KEY_SIZE = 1024;

    /**
     * 生成RSA算法的**对.
     * @return 返回存储**对的Map.
     * @throws Exception 可能的异常.
     */
    public static Map<String, String> generateDesKey() throws Exception {
        Map<String, String> keysMap = null;
        KeyPair keyPair = null;
        RSAPublicKey publicKey = null;
        RSAPrivateKey privateKey = null;
        KeyPairGenerator keyPairGenerator = null;
        // Key存储Map.
        keysMap = new HashMap<String, String>(2);
        // 生成RSA秘钥对.
        keyPairGenerator = KeyPairGenerator.getInstance(RSA_NAME);
        keyPairGenerator.initialize(KEY_SIZE);
        keyPair = keyPairGenerator.generateKeyPair();
        publicKey = (RSAPublicKey) keyPair.getPublic();
        privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 放置到存储Map.
        keysMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
        keysMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
        return keysMap;
    }

    /**
     * RAS基于Private**加密.
     * @param plainText 原文内容.
     * @param privateKey 私钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static String encodeTextByPrivateKey(String plainText, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            cipherBytes = encodeByRsa(plainText.getBytes(CHARSET_UTF8), privateKeyBytes, true);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPrivateKey.", ex);
            return "";
        }
    }

    /**
     * RAS基于Private**解密.
     * @param cipherText 密文内容.
     * @param privateKey 私钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static String decodeTextByPrivateKey(String cipherText, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] plainBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            plainBytes = decodeByRsa(Base64.decodeBase64(cipherText), privateKeyBytes, true);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPrivateKey.", ex);
            return "";
        }
    }

    /**
     * RAS基于Public**加密.
     * @param plainText 原文内容.
     * @param PublicKey 公钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static String encodeTextByPublicKey(String plainText, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            cipherBytes = encodeByRsa(plainText.getBytes(CHARSET_UTF8), publicKeyBytes, false);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPublicKey.", ex);
            return "";
        }
    }

    /**
     * RAS基于Public**解密.
     * @param cipherText 密文内容.
     * @param publicKey 公钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static String decodeTextByPublicKey(String cipherText, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] plainBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            plainBytes = decodeByRsa(Base64.decodeBase64(cipherText), publicKeyBytes, false);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPublicKey.", ex);
            return "";
        }
    }

    /**
     * RAS基于Private**加密.
     * @param plainBytes 原文内容.
     * @param privateKey 私钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] encodeBytesByPrivateKey(byte[] plainBytes, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            cipherBytes = encodeByRsa(plainBytes, privateKeyBytes, true);
            return cipherBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPrivateKey.", ex);
            return new byte[0];
        }
    }

    /**
     * RAS基于Private**解密.
     * @param cipherBytes 密文内容.
     * @param privateKey 私钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] decodeBytesByPrivateKey(byte[] cipherBytes, String privateKey) throws Exception {
        byte[] privateKeyBytes = null;
        byte[] plainBytes = null;
        try {
            privateKeyBytes = Base64.decodeBase64(privateKey);
            plainBytes = decodeByRsa(cipherBytes, privateKeyBytes, true);
            return plainBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPrivateKey.", ex);
            return new byte[0];
        }
    }

    /**
     * RAS基于Public**加密.
     * @param plainBytes 原文内容.
     * @param PublicKey 公钥.
     * @return 加密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] encodeBytesByPublicKey(byte[] plainBytes, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] cipherBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            cipherBytes = encodeByRsa(plainBytes, publicKeyBytes, false);
            return cipherBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.encodeTextByPublicKey.", ex);
            return new byte[0];
        }
    }

    /**
     * RAS基于Public**解密.
     * @param cipherBytes 密文内容.
     * @param publicKey 公钥.
     * @return 解密后内容.
     * @throws Exception 可能的异常.
     */
    public static byte[] decodeBytesByPublicKey(byte[] cipherBytes, String publicKey) throws Exception {
        byte[] publicKeyBytes = null;
        byte[] plainBytes = null;
        try {
            publicKeyBytes = Base64.decodeBase64(publicKey);
            plainBytes = decodeByRsa(cipherBytes, publicKeyBytes, false);
            return plainBytes;
        } catch (Exception ex) {
            logger.error("RSAUtil.decodeTextByPublicKey.", ex);
            return new byte[0];
        }
    }

    /**
     * 利用RSA进行加密,支持公钥和私钥.
     * @param plainBytes 待加密原文内容.
     * @param rsaKeyBytes RSA**.
     * @param isPrivateKey 是否私钥.
     * @return 加密结果.
     * @throws Exception 可能的异常.
     */
    public static byte[] encodeByRsa(byte[] plainBytes, byte[] rsaKeyBytes, boolean isPrivateKey) throws Exception {
        KeyFactory keyFactory = null;
        Key rsaKeyObj = null;
        Cipher cipher = null;
        PKCS8EncodedKeySpec pkcs8KeySpec = null;
        X509EncodedKeySpec x509KeySpec = null;
        int plainLength = plainBytes.length;
        byte[] cipherCacheBytes = null;
        int cipherPartTotal = 0;
        ByteArrayOutputStream baos = null;

        baos = new ByteArrayOutputStream();
        // 生成**算法对象.
        keyFactory = KeyFactory.getInstance(RSA_NAME);
        // 处理加密使用的Key.
        if (isPrivateKey) {
            pkcs8KeySpec = new PKCS8EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePrivate(pkcs8KeySpec);
        } else {
            x509KeySpec = new X509EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePublic(x509KeySpec);
        }
        cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        // 初始化算法**.
        cipher.init(Cipher.ENCRYPT_MODE, rsaKeyObj);
        // 计算分组,对报文进行分段加密.
        plainLength = plainBytes.length;
        cipherPartTotal = (int) Math.ceil((float) plainLength / MAX_ENCRYPT_BLOCK);
        for (int partIndex = 0; partIndex < cipherPartTotal; partIndex++) {
            if (partIndex == cipherPartTotal - 1) {
                cipherCacheBytes = cipher.doFinal(plainBytes, MAX_ENCRYPT_BLOCK * partIndex, plainLength);
            } else {
                cipherCacheBytes = cipher.doFinal(plainBytes, MAX_ENCRYPT_BLOCK * partIndex,
                        MAX_ENCRYPT_BLOCK * (partIndex + 1));
            }
            baos.write(cipherCacheBytes, 0, cipherCacheBytes.length);
        }
        return baos.toByteArray();
    }

    /**
     * 利用RSA进行解密,支持公钥和私钥.
     * @param cipherBytes 待解密原文内容.
     * @param rsaKeyBytes RSA**.
     * @param isPrivateKey 是否私钥.
     * @return 加密结果.
     * @throws Exception 可能的异常.
     */
    public static byte[] decodeByRsa(byte[] cipherBytes, byte[] rsaKeyBytes, boolean isPrivateKey) throws Exception {
        KeyFactory keyFactory = null;
        Key rsaKeyObj = null;
        Cipher cipher = null;
        PKCS8EncodedKeySpec pkcs8KeySpec = null;
        X509EncodedKeySpec x509KeySpec = null;
        int plainLength = cipherBytes.length;
        byte[] cipherCacheBytes = null;
        int cipherPartTotal = 0;
        ByteArrayOutputStream baos = null;

        baos = new ByteArrayOutputStream();
        // 生成**算法对象.
        keyFactory = KeyFactory.getInstance(RSA_NAME);
        // 处理加密使用的Key.
        if (isPrivateKey) {
            pkcs8KeySpec = new PKCS8EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePrivate(pkcs8KeySpec);
        } else {
            x509KeySpec = new X509EncodedKeySpec(rsaKeyBytes);
            rsaKeyObj = keyFactory.generatePublic(x509KeySpec);
        }
        cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        // 初始化算法**.
        cipher.init(Cipher.DECRYPT_MODE, rsaKeyObj);
        // 计算分组,对报文进行分段解密.
        plainLength = cipherBytes.length;
        cipherPartTotal = (int) ((float) plainLength / MAX_ENCRYPT_BLOCK);
        for (int partIndex = 0; partIndex < cipherPartTotal; partIndex++) {
            if (partIndex == cipherPartTotal - 1) {
                cipherCacheBytes = cipher.doFinal(cipherBytes, MAX_ENCRYPT_BLOCK * partIndex, plainLength);
            } else {
                cipherCacheBytes = cipher.doFinal(cipherBytes, MAX_ENCRYPT_BLOCK * partIndex,
                        MAX_ENCRYPT_BLOCK * (partIndex + 1));
            }
            baos.write(cipherCacheBytes, 0, cipherCacheBytes.length);
        }
        return baos.toByteArray();
    }

}

  工具类测试

package com.arhorchin.securitit.enordecryption.rsa;

import java.util.Map;

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

/**
 * @author Securitit.
 * @note RSAUtil测试类.
 */
public class RSAUtilTester {

    public static void main(String[] args) throws Exception {
        Map<String, String> keyMap = null;
        String publicKey = null;
        String privateKey = null;
        String plaintext = null;
        String ciphertext = null;
        byte[] cipherBytes = null;
        String dePlaintext = null;
        byte[] dePlainBytes = null;

        System.out.println("----------------------- 获取RSA**对 -------------------------");
        keyMap = RSAUtil.generateDesKey();
        publicKey = keyMap.get(RSAUtil.PUBLIC_KEY);
        privateKey = keyMap.get(RSAUtil.PRIVATE_KEY);
        System.out.println("公钥:" + publicKey);
        System.out.println("私钥:" + privateKey);
        System.out.println();
        System.out.println("----------------------- 字符串 公钥加密、私钥解密 -------------------------");
        plaintext = "这是一段数据原文-公钥加密的原文.";
        // 公钥进行加密示例.
        ciphertext = RSAUtil.encodeTextByPublicKey(plaintext, publicKey);
        System.out.println("公钥加密密文:" + ciphertext);
        // 私钥进行解密示例.
        dePlaintext = RSAUtil.decodeTextByPrivateKey(ciphertext, privateKey);
        System.out.println("私钥解密明文:" + dePlaintext);
        System.out.println();
        System.out.println("----------------------- 字符串 私钥加密、公钥解密 -------------------------");
        plaintext = "这是一段数据原文-私钥加密的原文.";
        // 私钥进行加密示例.
        ciphertext = RSAUtil.encodeTextByPrivateKey(plaintext, privateKey);
        System.out.println("私钥加密密文:" + ciphertext);
        // 公钥进行解密示例.
        dePlaintext = RSAUtil.decodeTextByPublicKey(ciphertext, publicKey);
        System.out.println("公钥解密明文:" + dePlaintext);
        System.out.println("----------------------- 字节数组 公钥加密、私钥解密 -------------------------");
        plaintext = "这是一段数据原文-公钥加密的原文.";
        // 公钥进行加密示例.
        cipherBytes = RSAUtil.encodeBytesByPublicKey(plaintext.getBytes("UTF-8"), publicKey);
        ciphertext = Base64.encodeBase64String(cipherBytes);
        System.out.println("公钥加密密文:" + ciphertext);
        // 私钥进行解密示例.
        dePlainBytes = RSAUtil.decodeBytesByPrivateKey(Base64.decodeBase64(ciphertext), privateKey);
        dePlaintext = new String(dePlainBytes, "UTF-8");
        System.out.println("私钥解密明文:" + dePlaintext);
        System.out.println();
        System.out.println("----------------------- 字节数组 私钥加密、公钥解密 -------------------------");
        plaintext = "这是一段数据原文-私钥加密的原文.";
        // 私钥进行加密示例.
        cipherBytes = RSAUtil.encodeBytesByPrivateKey(plaintext.getBytes("UTF-8"), privateKey);
        ciphertext = Base64.encodeBase64String(cipherBytes);
        System.out.println("私钥加密密文:" + ciphertext);
        // 公钥进行解密示例.
        dePlainBytes = RSAUtil.decodeBytesByPublicKey(Base64.decodeBase64(ciphertext), publicKey);
        dePlaintext = new String(dePlainBytes, "UTF-8");
        System.out.println("公钥解密明文:" + dePlaintext);
    }

}

  控制台输出

  查看Console中的控制台内容,明文和解密后明文对比,可以确认RSAUtil可以正常工作,控制台如下图:

----------------------- 获取RSA**对 -------------------------
公钥:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQAJFIhf5nNviRgssUabOvM8iqcrXCYmPBX9s37y9z41THaF3B+7Au1+jhGl482LFBRivVl6yeBpfHGT/uNyO9ld9oBo5qbIx7hEApkxHtfd6P4i2zWxlDyqcSxy5QyrZclH7wci8UFzrbQBKD/wKFu80Tft3Neu03HnbD70zOjQIDAQAB
私钥:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJAAkUiF/mc2+JGCyxRps68zyKpytcJiY8Ff2zfvL3PjVMdoXcH7sC7X6OEaXjzYsUFGK9WXrJ4Gl8cZP+43I72V32gGjmpsjHuEQCmTEe193o/iLbNbGUPKpxLHLlDKtlyUfvByLxQXOttAEoP/AoW7zRN+3c167TcedsPvTM6NAgMBAAECgYAkscBTtrFJI9zbV3TgUr8S2iM8K9bdHa1FzWNTMYPqB/fGiHW7xKL0jNgu5EU3RBCHDZaF6wx1iECM34ZG8Y4Nk4evaSvqxSpSyAEMWchln2K4KrAaHfvYBjy0MYz7/YXWdtYunaufDrFqBkCcB1Skfz6QUf9ryYOhPQnat+FggQJBAMZiXdClpmkzeZq7D+4ZU3VIw+cO/mPTjy1teKnqM6SNV+BuhdPy4aYy7yYGHdIlWBPx3O4P4d90L7sQ2E6BXJUCQQC50vY1PrvHq0vTQ6tKhDr+tTK6LkToOC9W8bNnYXYVBlAdB5CDtjUaoKcf9LIWSfU+1YRuGkte5nArXjK6yrQZAkA+4xnINWquOKIY2amwGZkqObnYOhmMPZlKlkRE4LgkNqYfwAluabT8QXMsA45aenoUQHx/fstkUWl8DFf1cu6NAkEApJQPs8DIF2PDWG2KfAj5JzXco8DvDq0UYHDZcCqFpsFcmxlkCQOLrPW0jzztrYf7SZdaHxnyvy5hEkfvrjhxoQJBAJAFJX26aaVXou1Dd5/Z5rqwi3Kc+d+HWM/54SBqxljKf0No1f0UW/MP4D5vFpXvnfI5a62NF+89Y4R3IejQIzg=

----------------------- 字符串 公钥加密、私钥解密 -------------------------
公钥加密密文:f0T4XxT6L2/t10/hhFD1NWriDgdAQNe9wLp34+Dkyn+w568GUDb8WZPbelmLoARzfz0DXI5fRFyRmbb9Zq5zqrxW1i/Ea0bs7cNnDQ23okPUNyIRdguMneAlrfi+WQgFJWXu9GUSMmFWMVgCAdtAX2I4YPXSmKuS3JX7fIslDxw=
私钥解密明文:这是一段数据原文-公钥加密的原文.

----------------------- 字符串 私钥加密、公钥解密 -------------------------
私钥加密密文:BYI5K56BuSuXp/0Thxc94Tck4W92+bDkeJEIP2qxjyQFst2RB+J6YXWp6LQBCMqEpwwEWgMDBv+U42V9nVMDCTDmugx2oqzT2xys7mMOIhQQsrccISCDzF/lk+CfrxY0hdEc4PJGrqn7vvCoKslBuJEgTL0uUxQirlJ6EVXc76g=
公钥解密明文:这是一段数据原文-私钥加密的原文.
----------------------- 字节数组 公钥加密、私钥解密 -------------------------
公钥加密密文:hvITbYLCnOhrCWDX/DgJNbuJTQWXXFzdPK6bVgep1MH99UyLO7nGKhqNViuVxuTqdVn1nh28Oz1ueA/PMNtiWCXHRUpVYgU957jfvoL17Eugyn9If81EJMpelBP9tdAb7lZJJiECkoUZpQvGImTNIYtONZA9dXGrakT15xO5m+I=
私钥解密明文:这是一段数据原文-公钥加密的原文.

----------------------- 字节数组 私钥加密、公钥解密 -------------------------
私钥加密密文:BYI5K56BuSuXp/0Thxc94Tck4W92+bDkeJEIP2qxjyQFst2RB+J6YXWp6LQBCMqEpwwEWgMDBv+U42V9nVMDCTDmugx2oqzT2xys7mMOIhQQsrccISCDzF/lk+CfrxY0hdEc4PJGrqn7vvCoKslBuJEgTL0uUxQirlJ6EVXc76g=
公钥解密明文:这是一段数据原文-私钥加密的原文.

  总结

​  算法实现都很类似,本文只是对算法实现做了整理,在Maven依赖引入的情况下,RSAUtil已经做了简单测试,可以直接使用。

  若文中存在错误和不足,欢迎指正!

本博微信公众号“超哥说码”,欢迎大家订阅,公众号正在完善中,会及时将更优质的博文推送于您!
非对称加密算法之Java RSA算法应用 附可用工具类