J
jimgardener
hi
i was trying to encrypt and decrypt a string using CipherOutputStream
and CipherInputStream as below.I wanted to write the encrypted string
to a file "encfile.enc" using CipherOutputStream and then read back
the decrypted version from that file using CipherInputStream
String plaintext="war starts tomorrow at 19 hours";
byte[] plainbytes=plaintext.getBytes("UTF-8");
KeyGenerator kg=KeyGenerator.getInstance("DES");
SecretKey skey=kg.generateKey();
byte[] deskey= skey.getEncoded();
SecretKeySpec spec=new SecretKeySpec(deskey,"DES");
Cipher cip=Cipher.getInstance("DES/ECB/PKCS5Padding");
cip.init(Cipher.ENCRYPT_MODE, spec);
CipherOutputStream cipout=new CipherOutputStream(new
FileOutputStream("encfile.enc"),cip);
cipout.write(plainbytes);
cipout.flush();
//now i init the cipher for decryption and use CipherInputStream
cip.init(Cipher.DECRYPT_MODE, spec);
CipherInputStream cipin=new CipherInputStream(new
FileInputStream("encfile.enc"),cip);
byte[] decryptedbytes=new byte[plainbytes.length];
cipin.read(decryptedbytes);
String decryptedtext=new String(decryptedbytes);
System.out.println("plain>>\n"+plaintext);
System.out.println("decrypted>>\n"+decryptedtext);
the result i get is
plain>>
war starts tomorrow at 19 hours
decrypted>>
war starts tomor
Here, after the 16 characters i am getting 'square like' characters.Am
i doing something wrong here?why doesn't the CipherInputStream read/
decrypt the full string?
i was trying to encrypt and decrypt a string using CipherOutputStream
and CipherInputStream as below.I wanted to write the encrypted string
to a file "encfile.enc" using CipherOutputStream and then read back
the decrypted version from that file using CipherInputStream
String plaintext="war starts tomorrow at 19 hours";
byte[] plainbytes=plaintext.getBytes("UTF-8");
KeyGenerator kg=KeyGenerator.getInstance("DES");
SecretKey skey=kg.generateKey();
byte[] deskey= skey.getEncoded();
SecretKeySpec spec=new SecretKeySpec(deskey,"DES");
Cipher cip=Cipher.getInstance("DES/ECB/PKCS5Padding");
cip.init(Cipher.ENCRYPT_MODE, spec);
CipherOutputStream cipout=new CipherOutputStream(new
FileOutputStream("encfile.enc"),cip);
cipout.write(plainbytes);
cipout.flush();
//now i init the cipher for decryption and use CipherInputStream
cip.init(Cipher.DECRYPT_MODE, spec);
CipherInputStream cipin=new CipherInputStream(new
FileInputStream("encfile.enc"),cip);
byte[] decryptedbytes=new byte[plainbytes.length];
cipin.read(decryptedbytes);
String decryptedtext=new String(decryptedbytes);
System.out.println("plain>>\n"+plaintext);
System.out.println("decrypted>>\n"+decryptedtext);
the result i get is
plain>>
war starts tomorrow at 19 hours
decrypted>>
war starts tomor
Here, after the 16 characters i am getting 'square like' characters.Am
i doing something wrong here?why doesn't the CipherInputStream read/
decrypt the full string?