Java文件加密spring属性文件加密Java认证考试

文章作者 100test 发表时间 2011:02:28 23:06:51
来源 100Test.Com百考试题网


  package com.happy.security.properties.

  import java.io.ByteArrayInputStream.

  import java.io.ByteArrayOutputStream.

  import java.io.File.

  import java.io.FileInputStream.

  import java.io.FileOutputStream.

  import java.io.InputStream.

  import java.io.ObjectInputStream.

  import java.io.ObjectOutputStream.

  import java.security.Key.

  import java.security.NoSuchAlgorithmException.

  import java.security.SecureRandom.

  import java.security.Security.

  import javax.crypto.Cipher.

  import javax.crypto.KeyGenerator.

  public class DESEncryptUtil {

  public static Key createKey() throws NoSuchAlgorithmException {//创建密钥

  Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1).

  KeyGenerator generator = KeyGenerator.getInstance("DES").

  generator.init(new SecureRandom()).

  Key key = generator.generateKey().

  return key.

  }

  public static Key getKey(InputStream is) {

  try {

  ObjectInputStream ois = new ObjectInputStream(is).

  return (Key) ois.readObject().

  } catch (Exception e) {

  e.printStackTrace().

  throw new RuntimeException(e).

  }

  }

  private static byte[] doEncrypt(Key key, byte[] data) {//对数据进行加密?

  try {

  Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding").

  cipher.init(Cipher.ENCRYPT_MODE, key).

  byte[] raw = cipher.doFinal(data).

  return raw.

  } catch (Exception e) {

  e.printStackTrace().

  throw new RuntimeException(e).

  }

  }

  public static InputStream doDecrypt(Key key, InputStream in) {//对数据进行解密?

  try {

  Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding").

  cipher.init(Cipher.DECRYPT_MODE, key).

  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().

  byte[] raw = cipher.doFinal(orgData).

  ByteArrayInputStream bin = new ByteArrayInputStream(raw).

  return bin.

  } catch (Exception e){

  e.printStackTrace().

  throw new RuntimeException(e).

  }

  }

  


相关文章


用Jsp来实现文件下载功能的几种方式Java认证考试
Java中string的特性Java认证考试
一个有意思的Java重载与多态问题Java认证考试
Java读写properties文件Java认证考试
Java文件加密spring属性文件加密Java认证考试
Java垃圾收集算法与内存泄露Java认证考试
jquery操作单选、复选、下拉Java认证考试
java匿名内部类的使用场景Java认证考试
JAVA:Eclipse代码自动提示Java认证考试
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛