zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    看门狗定时器
    fork 和 exec
    openwrt procd分析
    减肥经验总结
    gcc
    laravel5验证码
    laravel5通过auth.attempt事件加入登陆验证码
    双向链表
    mysql5.6源码安装
    laravel4通过控制视图模板路劲来动态切换主题
  • 原文地址:https://www.cnblogs.com/frankyou/p/5993685.html
Copyright © 2011-2022 走看看