RSA-兼容超长字符串

生成密钥对

    private static final int KEY_SIZE = 2048;
    public static final String KEY_ALGORITHM = "RSA";
    private static final int MAX_ENCRYPT_BLOCK = 117;
    private static final int MAX_DECRYPT_BLOCK = 256;


    /**
     * 生成密钥对
     *
     * @return 密钥对
     * @throws Exception 异常
     */
    public static Map<String, String> generateKeyPair() throws Exception {
        // 生成密钥
        SecureRandom secureRandom = new SecureRandom();
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(KEY_SIZE, secureRandom);
        KeyPair keyPair = generator.generateKeyPair();

        // 公钥,base64,否则为乱码
        Key publicKey = keyPair.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        String pubKey = new String(Base64.encodeBase64(publicKeyBytes));

        // 私钥,base64,否则为乱码
        Key privateKey = keyPair.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        String priKey = new String(Base64.encodeBase64(privateKeyBytes));

        Map<String, String> map = new HashMap<>(2);
        map.put("publicKey", pubKey);
        map.put("privateKey", priKey);
        return map;
    }

加密

    /**
     * 加密
     *
     * @param text      原文
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 异常
     */
    public static String encode(String text, String publicKey) throws Exception {
        Key key = getPublicKey(publicKey);
        // 构造Cipher
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] textBytes = text.getBytes();

        // 加密
        byte[] resultBytes = getBytes(cipher, textBytes, MAX_ENCRYPT_BLOCK);
        return new String(Base64.encodeBase64(resultBytes));
    }


    /**
     * 得到公钥
     *
     * @param key 密钥(base64编码)
     * @throws Exception 异常
     */
    private static PublicKey getPublicKey(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

解密

    /**
     * 解密
     *
     * @param encode     密文
     * @param privateKey 私钥
     * @return 原文
     * @throws Exception 异常
     */
    public static String decode(String encode, String privateKey) throws Exception {
        Key key = getPrivateKey(privateKey);
        // 构造Cipher
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] encodeBytes = Base64.decodeBase64(encode.getBytes());

        // 解密
        byte[] resultBytes = getBytes(cipher, encodeBytes, MAX_DECRYPT_BLOCK);
        return new String(resultBytes);
    }


    /**
     * 得到私钥
     *
     * @param key 密钥(base64编码)
     * @throws Exception 异常
     */
    private static PrivateKey getPrivateKey(String key) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

超长字符兼容处理

    /**
     * 加解密处理
     * 支持超长字符
     *
     * @param cipher      cipher
     * @param stringBytes 加密或解密字符串转换的bytes
     * @param maxBlock    分段大小
     * @return 加解密后的bytes
     * @throws Exception 异常
     */
    private static byte[] getBytes(Cipher cipher, byte[] stringBytes, int maxBlock) throws Exception {
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache;
        int inputLength = stringBytes.length;
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > maxBlock) {
                cache = cipher.doFinal(stringBytes, offSet, maxBlock);
                offSet += maxBlock;
            } else {
                cache = cipher.doFinal(stringBytes, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

调试结果

    public static void main(String[] args) throws Exception {
        Map<String, String> generateKeyPair = generateKeyPair();
        String privateKey = generateKeyPair.get("privateKey");
        String publicKey = generateKeyPair.get("publicKey");
        String text = "123456abcd!@#$";
        String encode = encode(text, publicKey);
        System.out.println("加密:" + encode);
        System.out.println("解密:" + decode(encode, privateKey));
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值