|
- package test;
- import java.io.*;
- import java.security.*;
- import javax.crypto.Cipher;
- import javax.crypto.CipherInputStream;
- import javax.crypto.CipherOutputStream;
- import javax.crypto.KeyGenerator;
- public class DesUtil {
- private static String keyfileName = "DesKey.xml";
- public static void decrypt(String file, String dest) throws Exception {
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.DECRYPT_MODE, getKey());
- InputStream is = new FileInputStream(file);
- OutputStream out = new FileOutputStream(dest);
- CipherOutputStream cos = new CipherOutputStream(out, cipher);
- byte[] buffer = new byte[1024];
- int r;
- while ((r = is.read(buffer)) >= 0) {
- cos.write(buffer, 0, r);
- }
- cos.close();
- is.close();
- out.close();
- }
- public static void encrypt(String file, String destFile) throws Exception {
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.ENCRYPT_MODE, getKey());
- InputStream is = new FileInputStream(file);
- OutputStream out = new FileOutputStream(destFile);
- CipherInputStream cis = new CipherInputStream(is, cipher);
- byte[] buffer = new byte[1024];
- int r;
- while ((r = cis.read(buffer)) > 0) {
- out.write(buffer, 0, r);
- }
- cis.close();
- is.close();
- out.close();
- }
- private static Key getKey() {
- Key kp = null;
- try {
- String fileName = keyfileName;
- InputStream is = new FileInputStream(fileName);
- ObjectInputStream oos = new ObjectInputStream(is);
- kp = (Key) oos.readObject();
- oos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return kp;
- }
- public static void main(String[] args) throws Exception {
- DesUtil.saveDesKey();
- DesUtil.encrypt("desinput.txt", "desoutput.txt");
- DesUtil.decrypt("desoutput.txt", "desinput2.txt");
- }
- public static void saveDesKey() {
- try {
- SecureRandom sr = new SecureRandom();
- KeyGenerator kg = KeyGenerator.getInstance("DES");
- kg.init(sr);
- FileOutputStream fos = new FileOutputStream(keyfileName);
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- Key key = kg.generateKey();
- oos.writeObject(key);
- oos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
复制代码 |
|