我在使用Java編寫RSA應用程序時遇到了問題。使用RSA加密長字符串(Java)
我必須從文件中讀取字符串,對其進行加密,然後將加密的字符串保存到新文件中。
我的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加密你的數據嗎?標準模式是使用RSA加密隨機對稱密鑰,並使用該對稱密鑰加密實際數據。 – CodesInChaos 2012-03-11 16:33:44
您應該收聽CodeInChaos,而不是使用RSA密鑰直接加密數據。這是違反所有良好做法的。此外,您的緩衝區大小根本不應與輸入大小相關。 – 2012-03-13 23:49:49