• Java RSA 分段加解密


     RSA加解密:

    1024位的证书,加密时最大支持117个字节,解密时为128;
    2048位的证书,加密时最大支持245个字节,解密时为256。

    加密时支持的最大字节数:证书位数/8 -11(比如:2048位的证书,支持的最大加密字节数:2048/8 - 11 = 245)

    public static byte[] decryptByPrivateKey(PrivateKey privateKey, byte[] encryptedData) throws Exception {
            Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
            cipher.init(2, privateKey);
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
    
            for(int i = 0; inputLen - offSet > 0; offSet = i * 256) {
                byte[] cache;
                if(inputLen - offSet > 256) {
                    cache = cipher.doFinal(encryptedData, offSet, 256);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
    
                out.write(cache, 0, cache.length);
                ++i;
            }
    
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        }
    
        public static byte[] encryptByPublicKey(PublicKey publicKey, byte[] data) throws Exception {
            Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
            cipher.init(1, publicKey);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
    
            for(int i = 0; inputLen - offSet > 0; offSet = i * 244) {
                byte[] cache;
                if(inputLen - offSet > 244) {
                    cache = cipher.doFinal(data, offSet, 244);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
    
                out.write(cache, 0, cache.length);
                ++i;
            }
    
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        }
  • 相关阅读:
    crontab机会任务监控
    Python 模块的一般处理
    MySQLdb autocommit
    MySQLdb callproc 方法
    Pthon MySQLdb 的安装
    CentOS7安装MySQL
    Linux中的网络
    Linux中的盘符问题
    类比的方法学习Performance_schema
    MySQL 设置数据库的隔离级别
  • 原文地址:https://www.cnblogs.com/frankyou/p/5993685.html
Copyright © 2020-2023  润新知