RSA加密 - Java


前言

  • 簡介
    RSA公開密鑰密碼體制是一種使用不同的加密密鑰與解密密鑰,“由已知加密密鑰推導出解密密鑰在計算上是不可行的”密碼體制。

  • 原理
    根據數論,尋求兩個大素數比較簡單,而將它們的乘積進行因式分解卻極其困難,因此可以將乘積公開作為加密密鑰,即公鑰,而兩個大素數組合成私鑰。公鑰是可發布的供任何人使用,私鑰則為自己所有,供解密之用。

  • 運算速度
    由於進行的都是大數計算,使得RSA最快的情況也比DES慢上好幾倍,無論是軟件還是硬件實現。速度一直是RSA的缺陷。一般來說只用於少量數據加密。RSA的速度比對應同樣安全級別的對稱密碼算法要慢1000倍左右。

  • 其他鏈接
    RSA加密 - Vue
    RSA分段加密 - Java
    RSA分段解密 - Vue


具體實現

  • 實現類
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @Description RSA加密算法
 * @author coisini
 * @date Jul 5, 2021
 * @Version 1.0
 */
public class RSAUtil {

    private static final String ALGO = "RSA";
    private static final String CHARSET = "UTF-8";

    /**
     * 公鑰 由generateKeyPair()生成
     */
    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaaI4MBywkCjIppZnraqN3pbrcZTq/t0+aMBo8K3pK9BDD6XkM6N2Yfcva7BSFbUWuAcI7piXak0UKn9CElDuhNzUSgQn4IXKxIt3Iva5cV83qYumj+0yRjjLT8Muu1Y1rgBZjY9oBwhVoV+Twg25+UJ+6Q6HM4xTwQQJDoyy4jwIDAQAB";

    /**
     * 私鑰 由generateKeyPair()生成
     */
    private static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJpojgwHLCQKMimlmetqo3elutxlOr+3T5owGjwrekr0EMPpeQzo3Zh9y9rsFIVtRa4BwjumJdqTRQqf0ISUO6E3NRKBCfghcrEi3ci9rlxXzepi6aP7TJGOMtPwy67VjWuAFmNj2gHCFWhX5PCDbn5Qn7pDoczjFPBBAkOjLLiPAgMBAAECgYBnBBKhG7frY5IMDxwd4Euna767hB4qAlbte+JE+ozgrOzyiDXm0wXk0yjKqm8WhczTRwEbYsImjdKmP/GSQoN1AU7yEzM8j0Jgq46m9ZVrHhu2NpuZpr+XueWnA6FNz6tybBgcCwA4t8dvfbOrvjqhrCu01O1xWIpjronyFBN4IQJBAPGuF58xjXyANnp5YU8NhUQ73tTIveRlOpMXDSYkf9lWG26XIGUIsTe0f5jssiNmYtxG+lUm9LLfZgOLcrVkDZ0CQQCjjrBNMXub49efVTCg+nCGT2QXW2BHg/qs5vu8Y34LUHoD/hoEJ+AOWOdnhpRoYOpBwJAm3Gu4a1VmZGGafp0bAkAdfY3aWhSWtZpwNXF/UPoLCnc1Zc1uGkAchLqRBfEn1w7/3qcQTRA66OaNBYzzLuIvWOXhECDZ1tK+6fw0UCItAkAOLibW6n1fDKf7JnWq30u2OVfiNofoa2bmarhUowOgk3+grP0wcwyX8dlOPnrLeeuVe86DsASe3p9u2zEjJesVAkEAhkLiv4TXrC1QlJl7ghksUfFmdT7M4Zxlzj10ConMgq68HkLdmn2nNLsjhUHGwJe3EqM6aozn4zw/Z7uPIT9Fsw==";

    /**
     * 生成密鑰對
     * @throws NoSuchAlgorithmException
     */
    private static void generateKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator 類用於生成公鑰和私鑰對,基於RSA算法生成對象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGO);
        // 初始化密鑰對生成器,密鑰大小為 96-1024 位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一個密鑰對,保存在 keyPair 中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私鑰
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公鑰
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
        // 得到私鑰字符串
        String privateKeyString = new String(Base64.getEncoder().encode((privateKey.getEncoded())));
        System.out.println(publicKeyString);
        System.out.println(privateKeyString);
    }

    /**
     * RSA公鑰加密
     * @param data 加密字符串
     * @return 密文
     * @throws Exception 加密過程中的異常信息
     */
    private static String encryptByPublicKey(String data) throws Exception {
        // base64 編碼的公鑰
        byte[] decoded = Base64.getDecoder().decode(PUBLIC_KEY);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(ALGO).generatePublic(new X509EncodedKeySpec(decoded));
        // RSA加密
        Cipher cipher = Cipher.getInstance(ALGO);
        // 公鑰加密
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(CHARSET)));
    }

    /**
     * RSA私鑰解密
     * @param data 加密字符串
     * @return 明文
     * @throws Exception 解密過程中的異常信息
     */
    private static String decryptByPrivateKey(String data) throws Exception {
        byte[] inputByte = Base64.getDecoder().decode(data.getBytes(CHARSET));
        // base64 編碼的私鑰
        byte[] decoded = Base64.getDecoder().decode(PRIVATE_KEY);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(ALGO).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        // RSA 解密
        Cipher cipher = Cipher.getInstance(ALGO);
        // 私鑰解密
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return new String(cipher.doFinal(inputByte));
    }

    /**
     * 私鑰加密
     * 前端公鑰解密
     * @param data 加密字符串
     * @return 密文
     * @throws Exception 加密過程中的異常信息
     */
    public static String encryptByPrivateKey(String data) throws Exception {
        // 獲取私鑰
        PrivateKey privateKey = getPrivateKey(PRIVATE_KEY);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] cipherText = cipher.doFinal(data.getBytes());
        String cipherStr = Base64.getEncoder().encodeToString(cipherText);
        return cipherStr;
    }

    /**
     * 公鑰解密
     * @param data 解密字符串
     * @return 明文
     * @throws Exception 解密過程中的異常信息
     */
    public static String decryptByPublicKey(String data) throws Exception {
        // 獲取公鑰
        PublicKey publicKey = getPublicKey(PUBLIC_KEY);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] cipherText = Base64.getDecoder().decode(data);
        byte[] decryptText = cipher.doFinal(cipherText);
        return new String(decryptText);
    }

    /**
     * 將base64編碼后的私鑰字符串轉成PrivateKey實例
     * @param privateKey 私鑰
     * @return PrivateKey實例
     * @throws Exception 異常信息
     */
    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGO);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 將base64編碼后的公鑰字符串轉成PublicKey實例
     * @param publicKey 公鑰
     * @return PublicKey實例
     * @throws Exception 異常信息
     */
    private static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGO);
        return keyFactory.generatePublic(keySpec);
    }


    public static void main(String[] args) {
        String data = "RSA encrypt!";
        try {
            // generateKeyPair();

            String encryDataByPublicKey = encryptByPublicKey(data);
            System.out.println("encryDataByPublicKey: " + encryDataByPublicKey);
            String decryDataByPrivateKey = decryptByPrivateKey(encryDataByPublicKey);
            System.out.println("decryDataByPrivateKey: " + decryDataByPrivateKey);

            String encryDataByPrivateKey = encryptByPrivateKey(data);
            System.out.println("encryDataByPrivateKey: " + encryDataByPrivateKey);
            String decryDataByPublicKey = decryptByPublicKey(encryDataByPrivateKey);
            System.out.println("decryDataByPublicKey: " + decryDataByPublicKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  • 結果如下所示:
    在這里插入圖片描述
- End -
一個努力中的公眾號
關注一下吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM