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; 
    }

 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/15844.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论