Java -- RSA 非对称加密算法工具类

Java -- RSA 非对称加密算法工具类,第1张

什么是RSA算法

RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的

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

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

详细原理参见RSA算法

RSA算法工具类 源码
import org.apache.commons.codec.binary.Base64;

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

/**
 * @ClassName: RSAUtil
 * @Description: RSA非对称加密算法工具类
 */

public class RSAUtil {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    public static void main(String[] args) throws Exception {
        Map<String, String> keyMap = RSAUtil.createKeys(1024);
        String publicKey = keyMap.get("publicKey");
        String privateKey = keyMap.get("privateKey");
        printMsg("公钥: %s", publicKey);
        printMsg("私钥: %s", privateKey);

        String str = "不到长城非好汉";
        printMsg("明文:%s, 长度:%d", str, str.getBytes().length);

        printMsg("公钥加密----私钥解密");
        String encodedData = RSAUtil.publicEncrypt(str, RSAUtil.getPublicKey(publicKey));
        printMsg("密文:%s", encodedData);
        String decodedData = RSAUtil.privateDecrypt(encodedData, RSAUtil.getPrivateKey(privateKey));
        printMsg("解密后文字: %s", decodedData);

        printMsg("私钥加密----公钥解密");
        encodedData = RSAUtil.privateEncrypt(str, RSAUtil.getPrivateKey(privateKey));
        printMsg("密文:%s", encodedData);
        decodedData = RSAUtil.publicDecrypt(encodedData, RSAUtil.getPublicKey(publicKey));
        printMsg("解密后文字: %s", decodedData);
    }

    public static void printMsg(String format, Object... args) {
        System.out.println(String.format(format, args));
    }

    /**
     * 为RSA算法创建一个KeyPairGenerator对象(KeyPairGenerator,密钥对生成器,用于生成公钥和私钥对)
     *
     * @param keySize
     * @return
     */
    public static Map<String, String> createKeys(int keySize) {
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        KeyPair keyPair = kpg.generateKeyPair();
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());

        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());

        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 获取公钥
     *
     * @param publicKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 获取私钥
     *
     * @param privateKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }

        byte[] resultDatas = null;

        int offSet = 0;
        byte[] buff;
        int i = 0;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
            resultDatas = out.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        return resultDatas;
    }
}
结果输出示例
公钥: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgneHE8CBOH9YpBaNGF-hu-O6p_Ap9fM38q1uaCY5lDj4P3GHl3WuMjJztoM5gwHQS7va64tqw9soFdi7XI8SawEP4jz2435dHCwv_iwqnwFKFSc92DPkNsYZGw7iCkjiFN-_o7QMJ6hXyFWE3q4ua9QmpZWHoar--ngg34rZC9QIDAQAB
私钥: MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKCd4cTwIE4f1ikFo0YX6G747qn8Cn18zfyrW5oJjmUOPg_cYeXda4yMnO2gzmDAdBLu9rri2rD2ygV2LtcjxJrAQ_iPPbjfl0cLC_-LCqfAUoVJz3YM-Q2xhkbDuIKSOIU37-jtAwnqFfIVYTeri5r1CallYehqv76eCDfitkL1AgMBAAECgYEAn27ZEwJBLwuPLD06a3OD99QGJJnZV-MxHaSDUw41WL6ggGIEk4YNIgDaLU84TPX8wmaOZ8iTyKHQu0crC8eneVlQ95gaJJHAeTu5X_vsGB_fBIscjc8bT412UbTrKF3qGGlYJSx5woDXgIFCRe05F3ZhwMj93-_npsTtbaE7BoECQQDdTcaAcIZGEc_clZrZCqlTKfzJ2D3LLqazVxNgeb2PGx21f5FNoB9UXUM0--LZNRXnkpk1gbM6_IZLxBG-6pIxAkEAucxgaQFMBX21l8YQ_x0bMVrKtoDOYstsQVG7O8eZWdY5KbzHBIBdDKKR5RFZg61l8WsKYjROmdVXxOXH57XoBQJABW4LGMup_74gI4FoMzsXvHqjQTCVE48pd-0DBLL3-7Lmn7Vpk0YCfsdrBrnHbxzmVLA8Ihv0kdXwVZuR8-U9gQJAIO54qCPytYZyiVQx7wXZrAXLqE1sR1aG-YzjAtV9-M5fk2ZCYCngVDz8Xv2UQCKbzw6J6J4c0GdgByYzKH61gQI_Brbi7mGZ9FclisIcu2XLc5S9KdWqaOoYrwV36G5t5CfXjRtCPMz8V7Owa9O6lpaDm9Y8EkMiEnwbkd_VtKD8
明文:不到长城非好汉, 长度:21
公钥加密----私钥解密
密文:CcNsy-4dprsQoTD6q_64abzmypwAgT3UOdrur2ZLtbFIgRwNRwpt7GeqkbQs2Vj0h4x5ANsb17Pfiarl2Ajdlf8L-Ox_lOrp05tYicYypBMGDGbFTVqEGXcjzzVBWu-QPh0MWiTW6FdpIb1FW6KkkWi3ISzL7B3ZbW34tVBbsh0
解密后文字: 不到长城非好汉
私钥加密----公钥解密
密文:IiLm174Eg8aPDHUIU6s77EtfCF-I4kTD_ZuoWvR8ZTm4SW5PFjpzskY6I96tFxxWDsgm0WJD3g82LD3maLKs4LLDH8PpkyjNgfq_B7vyACSRf-BuiOHwFPJB8gUlxcwo436Nb7HirMbTzlpBBL3U5u3Ywiuh5gLNwahlzEIM6pE
解密后文字: 不到长城非好汉

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/870904.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存