RAS加密

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {

    /**
     * 生成RSA密钥对(2048位)
     */
    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 推荐使用2048位密钥
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 公钥加密(支持长文本分组加密)
     * @param plainText 明文
     * @param publicKey 公钥
     */
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        
        // 获取最大加密块大小
        int keySize = 2048;
        int maxBlockSize = keySize / 8 - 11; 
        
        byte[] data = plainText.getBytes();
        int dataLength = data.length;
        StringBuilder encryptedText = new StringBuilder();
        
        // 分段加密
        for (int offset = 0; offset < dataLength; offset += maxBlockSize) {
            int blockSize = Math.min(maxBlockSize, dataLength - offset);
            byte[] encryptedBlock = cipher.doFinal(data, offset, blockSize);
            encryptedText.append(Base64.getEncoder().encodeToString(encryptedBlock));
        }
        
        return encryptedText.toString();
    }

    /**
     * 私钥解密(支持分组解密)
     * @param encryptedText 密文
     * @param privateKey 私钥
     */
    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        
        // 计算解密块大小
        int keySize = 2048;
        int blockSize = keySize / 8;
        
        byte[] data = Base64.getDecoder().decode(encryptedText);
        int dataLength = data.length;
        StringBuilder decryptedText = new StringBuilder();
        
        // 分段解密
        for (int offset = 0; offset < dataLength; offset += blockSize) {
            int currentBlockSize = Math.min(blockSize, dataLength - offset);
            byte[] decryptedBlock = cipher.doFinal(data, offset, currentBlockSize);
            decryptedText.append(new String(decryptedBlock));
        }
        
        return decryptedText.toString();
    }

    /**
     * 公钥对象转Base64字符串
     */
    public static String publicKeyToString(PublicKey publicKey) {
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }

    /**
     * 私钥对象转Base64字符串
     */
    public static String privateKeyToString(PrivateKey privateKey) {
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }

    /**
     * Base64字符串转公钥对象
     */
    public static PublicKey stringToPublicKey(String publicKeyStr) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    }

    /**
     * Base64字符串转私钥对象
     */
    public static PrivateKey stringToPrivateKey(String privateKeyStr) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(spec);
    }

    public static void main(String[] args) throws Exception {
        // 1. 生成密钥对
        KeyPair keyPair = generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        
        // 2. 密钥转换为字符串(方便存储)
        String publicKeyStr = publicKeyToString(publicKey);
        String privateKeyStr = privateKeyToString(privateKey);
        System.out.println("公钥(Base64):\n" + publicKeyStr);
        System.out.println("\n私钥(Base64):\n" + privateKeyStr);
        
        // 3. 加密测试
        String originalText = "这是一段需要加密的敏感数据,RSA非对称加密演示!";
        System.out.println("\n原始文本: " + originalText);
        
        String encryptedText = encrypt(originalText, publicKey);
        System.out.println("\n加密结果(Base64):\n" + encryptedText);
        
        // 4. 解密测试
        String decryptedText = decrypt(encryptedText, privateKey);
        System.out.println("\n解密结果: " + decryptedText);
        
        // 5. 验证结果
        System.out.println("\n解密是否成功: " + originalText.equals(decryptedText));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值