簡體   English   中英

使用RSA(Java)加密長字符串

[英]Encrypt long String with RSA (Java)

我在使用Java時遇到的RSA應用程序出現問題。

我必須從文件中讀取一個字符串,對其進行加密,然后將加密的字符串保存在一個新文件中。

我的RSA密鑰長度為1024位。

問題所在的代碼部分如下:

            readBytes = in.read(bytesToBeEncoded, 0, bytesToBeEncoded.length);

            while(readBytes != -1){
                encodedContent = ciph.update(bytesToBeEncoded, 0, readBytes);
                out.write(encodedContent);
                bytesToBeEncoded= new byte[(KEY_SIZE/8)-11];
                readBytes = in.read(bytesToBeEncoded, 0, bytesToBeEncoded.length);                  
            }

            encodedContent = ciph.doFinal();
            out.write(encodedContent);

變量定義如下:

        byte[] bytesToBeEncoded = new byte[(KEY_SIZE/8)-11]; 

        FileInputStream in = new FileInputStream(new File(file1));
        FileOutputStream out = new FileOutputStream(new File(file2));
        int readBytes;

關鍵是當我加密一個小於117字節的字符串時,它完美地工作(加密然后解密),但是當大小更大時,應用程序拋出此異常:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes

拋出:

encodedContent = ciph.doFinal();

我不知道問題出在哪里以及我必須做什么。

誰能幫助我? 謝謝。

抱歉我的英語。

問題在於如何初始化正在讀取輸入的字節數組。 您正在根據RSA密鑰的大小而不是輸入流的預期大小來設置大小。

byte[] bytesToBeEncoded = new byte[(KEY_SIZE/8)-11];

密鑰大小為1024位,因此1024/8 -11 = 128 - 11 = 117字節。 這是您可以從流中讀取的數據量,而不應與RSA密鑰的大小相關。

您應該將字節數組初始化為您需要讀入的最大數據大小,這將避免異常。 例如:

byte[] bytesToBeEncoded = 1024;

允許最大輸入字符串為1024個字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM