Java文件加密

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

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

  System.out.println(“===================”);

  if (args.length == 2 && args[0].equals(“key”)){

  Key key = DESEncryptUtil.createKey();

  ObjectOutputStream oos = new ObjectOutputStream(

  new FileOutputStream(args[1]));

  oos.writeObject(key);

  oos.close();

  System.out.println(“成功生成密钥文件”);

  } else if (args.length == 3 && args[0].equals(“encrypt”)){

  File file = new File(args[1]);

  FileInputStream in = new FileInputStream(file);

  ByteArrayOutputStream bout = new ByteArrayOutputStream();

  byte[] tmpbuf = new byte[1024];

  int count = 0;

  while ((count = in.read(tmpbuf)) != -1){

  bout.write(tmpbuf, 0, count);

  tmpbuf = new byte[1024];

  }

  in.close();

  byte[] orgData = bout.toByteArray();

  Key key = getKey(new FileInputStream(args[2]));

  byte[] raw = DESEncryptUtil.doEncrypt(key, orgData);

  file = new File(file.getParent() + “\\en_” + file.getName());

  FileOutputStream out = new FileOutputStream(file);

  out.write(raw);

  out.close();

  System.out.println(“成功加密,加密文件位:”+file.getAbsolutePath());

  } else if (args.length == 3 && args[0].equals(“decrypt”)){//对文件进行解密

  File file = new File(args[1]);

  FileInputStream fis = new FileInputStream(file);

  Key key = getKey(new FileInputStream(args[2]));

  InputStream raw = DESEncryptUtil.doDecrypt(key, fis);

  ByteArrayOutputStream bout = new ByteArrayOutputStream();

  byte[] tmpbuf = new byte[1024];

  int count = 0;

  while ((count = raw.read(tmpbuf)) != -1){

  bout.write(tmpbuf, 0, count);

  tmpbuf = new byte[1024];

  }

  raw.close();

  byte[] orgData = bout.toByteArray();

  file = new File(file.getParent() + “\\rs_” + file.getName());

  FileOutputStream fos = new FileOutputStream(file);

  fos.write(orgData);

  System.out.println(“成功解密,解密文件位:”+file.getAbsolutePath());

  }else if(args.length==1 && args[0].equals(“-h”)) {

  System.out.println(“\t文件加密解密\n”);

  System.out.println(“创建密钥文件:java -jar key.jar key E:/key.dat”);

  System.err.println(“其中key.jar为需要运行的Jar文件,key参数表示要创建加密文件 E:/key.dat表示加密文件的存放位置”);

  System.out.println(“\n”);

  System.out.println(“加密文件:java -jar key.jar encrypt E:/test.properties E:/key.dat “);

  System.err.println(“其中key.jar为需要运行的Jar文件 encrypt 参数表示加密 E:/test.properties表示需要加密的文件 E:/key.dat表示加密密钥文件”);

  System.out.println(“\n”);

  System.out.println(“解密文件:java -jar key.jar decrypt E:/en_test.properties E:/key.dat “);

  System.err.println(“其中key.jar为需要运行的Jar文件 decrypt参数表示解密 E:/en_test.properties表示需要解密的文件 E:/key.dat表示解密的密钥文件”);

  }else {

  System.out.println(“你需要运行参数-h”);

  }

  }

  }

[1][2]

生活中若没有朋友,就像生活中没有阳光一样

Java文件加密

相关文章:

你感兴趣的文章:

标签云: