Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

CipherOutputStream writes only one line

843811Jun 12 2006 — edited Jun 26 2006
Hi Together,

I am a newby to Cryptography so maybe somebody can give me a little help please.

I thought I am doing very well for the first time, but unfortunately my code is not working.

What I want to do:
----------------------
At the end I want to read some files and encrypt them.

My Problem:
---------------
The encrypt.txt and decrypt.txt file are empty (0 kb).

The content of the text.txt file is as follows:
Looks like the code works if the file has only this one and only line.
If here is another line in the file the entrypted file is empty.


As the content of the text.txt file says, if the file has only one line the whole thing works fine. As soon as I add another line, or even use another file, I always have 0 kb files.

This is my code:
-------------------
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class PubPrivKeyTest {
	
	public static void main( String args[] ) throws Exception {

		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		keyPairGen.initialize(1024); //1024 is max key length
		KeyPair keyPair = keyPairGen.generateKeyPair();
		PrivateKey privKey = keyPair.getPrivate();
		PublicKey pubKey = keyPair.getPublic(); 
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        
		// InputStream for source file
		InputStream fin = new FileInputStream("c:/text.txt");
		// Stream for writing encrypted file
		CipherOutputStream cos = new CipherOutputStream(new
				FileOutputStream("C:/encrypt.txt"), cipher);

		byte[] bufferIn = new byte[1024];
                int lenIn;
                while ((lenIn = fin.read(bufferIn)) != -1) {
                      cos.write(bufferIn, 0, lenIn);
                } // end while
		
                cos.close();
                fin.close();	
        
		System.out.println("Encrypted!");	
		
		// and decrypt again
		cipher.init(Cipher.DECRYPT_MODE, privKey);
		CipherInputStream cis = new CipherInputStream( new
				FileInputStream("C:/encrypt.txt"), cipher);
                OutputStream fos = new FileOutputStream("C:/decrypt.txt");
        
                byte[] bufferOut = new byte[1024];
                int lenOut;
                while ((lenOut = cis.read(bufferOut)) > 0) {
        	        fos.write(bufferOut, 0, lenOut);
               }// end while
        
               cis.close();
               fos.close();
        
               System.out.println("Decrypted!");
    
         }
}
Thanks for your help.

IceBear
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 24 2006
Added on Jun 12 2006
7 comments
712 views