2012-12-04 65 views
2

我試圖用BigInteger在Java中實現RSA加密和解密文件。使用BigInteger手動實現Java中的RSA

我有我的參數P,Q,E,N,d

我文件讀入一個byte []

System.out.println("Opening file: " + infile); 
File file = new File(infile); 
FileInputStream fis = new FileInputStream(file); 
int filelength = (int)file.length(); 
byte[] filecontent = new byte[filelength]; 
fis.read(filecontent); 
fis.close(); 

,然後從字節[]

做一個BigInteger
BigInteger plaintext = new BigInteger(filecontent); 

然後加密簡直是

BigInteger ciphertext = plaintext.modPow(e, n); 

我寫密文到一個新的加密文件

FileOutputStream fos = new FileOutputStream(outfile); 
fos.write(ciphertext.toByteArray()); 
fos.close(); 

解密是大同小異的

BigInteger plaintext = ciphertext.modPow(d, n); 

這工作完全正常,當我第一次與一個小的文本文件進行了測試。它加密和解密很好。然而,當我開始測試一些其他文件,如JPG或ZIP,一切都崩潰了。我無法指出調試問題,但我注意到有時從文件byte []到BigInteger的轉換會導致一個空的BigInteger對象。

在加密之前,我必須對字節[]做些什麼嗎?

+0

你是什麼意思'一切都分崩離析'? –

+0

你最好將文件內容分割成塊並分別進行加密。 –

+0

我會得到空的加密文件,當然後來還會得到不正確的解密文件。 關於如何分割文件的任何建議? – bennyboy

回答

2

爲了解決這個問題,你需要把文件分成塊,這意味着例如每隔256位作爲一個部分並加密它,等等。