Decrypting “long” message encrypted with RSA java

前端 未结 2 1420
谎友^
谎友^ 2020-12-29 16:07

Hi this is the same question, that was asked two years ago: Java/JCE: Decrypting “long” message encrypted with RSA

I had a large byte array and rsa keypair, initiate

2条回答
  •  余生分开走
    2020-12-29 17:06

    If you do need to encrypt/decrypt long strings using RSA, then you can break the bytes up in to smaller "chunks" and process each chunk of bytes through the cipher one at a time while storing the results in a ByteBuffer.

    Encryption:

    byte[] encData = null;
    try {
    
        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);
    
        Cipher pkCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        pkCipher.init(Cipher.ENCRYPT_MODE, pk);
    
        int chunkSize = 117; // 1024 / 8 - 11(padding) = 117
        int encSize = (int) (Math.ceil(data.length/117.0)*128);
        int idx = 0;
        ByteBuffer buf = ByteBuffer.allocate(encSize);
        while (idx < data.length) {
            int len = Math.min(data.length-idx, chunkSize);
            byte[] encChunk = pkCipher.doFinal(data, idx, len);
            buf.put(encChunk);
            idx += len;
        }
    
        // fully encrypted data     
        encData = buf.array();
    } catch (Exception e) {
        e.printStackTrace();
    

    Decryption

    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    rsaCipher.init(Cipher.DECRYPT_MODE, rsaPk);
    
    int chunkSize = 128;
    int idx = 0;
    ByteBuffer buf = ByteBuffer.allocate(data.length);
    while(idx < data.length) {
        int len = Math.min(data.length-idx, chunkSize);
        byte[] chunk = rsaCipher.doFinal(data, idx, len);
        buf.put(chunk);
        idx += len;
    }
    
    // fully decrypted data
    byte[] decryptedData = buf.array();
    

提交回复
热议问题