?
Solved

the encrypted file is cutted shorter

Posted on 2006-04-10
6
Medium Priority
?
518 Views
Last Modified: 2012-05-05
hello
my code as following:


public class EncryptHandler {

public EncryptHandler() {
}

public SecretKey genKey() {
try {
KeyGenerator kg = KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey key = kg.generateKey();
return key;
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
return null;
}
}

public SecretKey readKey(String path) {
try {
FileInputStream fin = new FileInputStream(path);
int num = fin.available();
byte[] keykb = new byte[num];
fin.read(keykb);

SecretKeySpec key = new SecretKeySpec(keykb, "DESede");
return key;

} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
return null;
}
}

public void saveKeyAsObject(SecretKey key, String destPath) {
try {
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
destPath));
o.writeObject(key);
} catch (Exception e) {
System.exit(-1);
e.printStackTrace();
}

}

public void saveKeyAsByte(SecretKey key, String destPath) {
try {
byte[] kb = key.getEncoded();
FileOutputStream fo = new FileOutputStream(destPath);
fo.write(kb);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}

}

public void encryptFile(String srcPath, String destPath, SecretKey key) {
try {

Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, key);

BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(srcPath)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new CipherOutputStream(new FileOutputStream(destPath), cp)));

String tmpStr = "";
while ((tmpStr = reader.readLine()) != null) {

writer.write(tmpStr + "\n");
writer.flush();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}

public void decryptFile(String srcPath, String destPath, SecretKey key) {
try {
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, key);
BufferedReader reader = new BufferedReader(new InputStreamReader(
new CipherInputStream(new FileInputStream(srcPath), cp)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(destPath)));
String tmpStr = "";
while ((tmpStr = reader.readLine()) != null) {
writer.write(tmpStr + "\n");
writer.flush();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}

}

public static void main(String[] argv) {
String s = "Hello world!!!!";
EncryptHandler c = new EncryptHandler();
SecretKey key = c.genKey();
c.saveKeyAsByte(key, "c:\\temp\\testkey1");
SecretKey k = c.readKey("c:\\temp\\testkey1");
c.encryptFile("c:\\temp\\newpasswords", "c:\\temp\\oooo", key);
c.decryptFile("c:\\temp\\oooo", "c:\\temp\\ttttt", key);

}
}




i use symetrical key encrypt text firle the flow as follow:
1 generate key
2 save the key to the disk
3 read the key from disk
4 encrypt a text file
5 decrypt the file generated in step 4

but i find the final text file is cutted shortter then the original one, and i think the such problem result from "encryptFile" method, i guess it maybe result from the "padding" problem, but i don't know how to solve it, i am a beginner, who can help me?

thank you very much!!
0
Comment
Question by:zbcong
6 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 16416380
Don't use Reader and Writer - they may subject the stream to mutation
0
 
LVL 13

Expert Comment

by:Kelvin_King
ID: 16416856
I wrote a little program a while back to encrypt and decrypt using DES. Maybe you can have a look at it to have an idea on it's done. The only difference is, I hard coded the keys into the program, but it's pretty easy to modify it to read from a file. Hope it helps.

//-----------------------------------------------------------------------------
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class DES {

      public static void main(String args[]) throws Exception {
      
            FileInputStream fi = new FileInputStream(args[1]);
            FileOutputStream fo = new FileOutputStream(args[2]);
            byte[] key = { 9 , 5, 1, 9, 3, 7, 13, 17 };
            byte[] iv = { 2, 3, 5, 7, 11, 5, 1, 8 };
            if(args[0].equals("e"))
            Encrypt(fi, fo, key, iv);
            else if(args[0].equals("d"))
            Decrypt(fi, fo, key, iv);
            else
            System.out.println("Usage: java filename <option (e/d)> <input file> <output file>");
            fi.close();
            fo.close();
      }
      
      //function for decryption
      public static void Decrypt(InputStream fi, OutputStream fo, byte[] key, byte[] iv) throws Exception {
            long startTime, endTime;
            double avgTime;
            int totalBytes, bytesRead;
            byte[] buffer = new byte[1024];
            byte[] buf;
            startTime = System.currentTimeMillis();
            
            Cipher cipher;
            cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            SecretKeySpec desKey = new SecretKeySpec(key, "DES");
            IvParameterSpec IV = new IvParameterSpec(iv,0,8);
            cipher.init(Cipher.DECRYPT_MODE, desKey, IV);
            
          bytesRead = fi.read(buffer);
            totalBytes = bytesRead;
            while(bytesRead > 0) {
                  buf = cipher.update(buffer,0,bytesRead);
                  bytesRead = fi.read(buffer);
                  totalBytes += bytesRead;
                  fo.write(buf);
            }
            
            buf = cipher.doFinal();
            fo.write(buf);
            
            endTime = System.currentTimeMillis();
            
            avgTime = ((endTime-startTime)*1e6) / totalBytes;
            System.out.println("Time taken DES encryption: " + avgTime + " ns/byte ");
      }
      
      //function for encryption
      public static void Encrypt(InputStream fi, OutputStream fo, byte[] key, byte[] iv) throws Exception {
            long startTime, endTime;
            double avgTime;
            int totalBytes, bytesRead;
            byte[] buffer = new byte[1024];
            byte[] buf;
            startTime = System.currentTimeMillis();
            
            Cipher cipher;
            cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            SecretKeySpec desKey = new SecretKeySpec(key, "DES");
            IvParameterSpec IV = new IvParameterSpec(iv,0,8);
            cipher.init(Cipher.ENCRYPT_MODE, desKey, IV);
            
            bytesRead = fi.read(buffer);
            totalBytes = bytesRead;
            while(bytesRead > 0) {
                  buf = cipher.update(buffer,0,bytesRead);
                  bytesRead = fi.read(buffer);
                  totalBytes += bytesRead;
                  fo.write(buf);
            }
            
            buf = cipher.doFinal();
            fo.write(buf);
            
            endTime = System.currentTimeMillis();
            avgTime = ((endTime-startTime)*1e6) / totalBytes;
            System.out.println("Time taken DES decryption: " + avgTime + " ns/byte");
      }
}
0
 
LVL 13

Accepted Solution

by:
Webstorm earned 500 total points
ID: 16416937
Don't forget to call the close() methods when you open an output stream :
public void saveKeyAsObject(SecretKey key, String destPath) {
try {
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
destPath));
o.writeObject(key);
o.close(); // <--
} catch (Exception e) {
System.exit(-1);
e.printStackTrace();
}

}

public void saveKeyAsByte(SecretKey key, String destPath) {
try {
byte[] kb = key.getEncoded();
FileOutputStream fo = new FileOutputStream(destPath);
fo.write(kb);
fo.close(); // <--
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}

}

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 13

Expert Comment

by:Webstorm
ID: 16416956

public void encryptFile(String srcPath, String destPath, SecretKey key) {
try {

Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, key);

BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(srcPath)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new CipherOutputStream(new FileOutputStream(destPath), cp)));

String tmpStr = "";
while ((tmpStr = reader.readLine()) != null) {

writer.write(tmpStr + "\n");
writer.flush();
write.close(); // <----
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}

public void decryptFile(String srcPath, String destPath, SecretKey key) {
try {
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, key);
BufferedReader reader = new BufferedReader(new InputStreamReader(
new CipherInputStream(new FileInputStream(srcPath), cp)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(destPath)));
String tmpStr = "";
while ((tmpStr = reader.readLine()) != null) {
writer.write(tmpStr + "\n");
writer.flush();
write.close(); // <----
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}

}
0
 

Author Comment

by:zbcong
ID: 16443526
thanks for all of your helps very much
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16443813
:-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month15 days, 12 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question