Java Cryptographic Extension (JCE) 框架的核心应用

 

本文简单介绍了JCE框架的核心应用!

javax.crypto.Cipher此类为加密和解密提供密码功能。它构成了 Java Cryptographic Extension (JCE) 框架的核心。为创建 Cipher 对象,应用程序调用 Cipher 的 getInstance 方法并将所请求转换 的名称传递给它。还可以指定提供者的名称(可选)。

转换 是一个字符串,它描述为产生某种输出而在给定的输入上执行的操作(或一组操作)。转换始终包括加密算法的名称(例如,DES),后面可能跟有一个反馈模式和填充方案。

package thtf.com.cn.client;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

//JCE应用
public class MainEncrypt {

 static String keyFile = "c:/key.xml";

 static Properties property = getProperties();

 Cipher ecipher;

 Cipher dcipher;

 private final String JDBCPROPERTIES_PATH = "socket_jdbc.properties";

 /**
  * 生成密钥。
  *
  */
 public static void saveDesKey() {
  try {

   keyFile = property.getProperty("keyFile");
   SecureRandom sr = new SecureRandom();
   // 为我们选择的DES算法生成一个KeyGenerator对象
   KeyGenerator kg = KeyGenerator.getInstance("DES");
   kg.init(sr);
   FileOutputStream fos = new FileOutputStream(keyFile);
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   // 生成密钥
   SecretKey key = kg.generateKey();
   oos.writeObject(key);
   oos.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * 得到密钥。
  *
  * @return
  */
 public static SecretKey getKey() {
  SecretKey kp = null;
  try {
   keyFile = property.getProperty("keyFile");
   // String fileName = "conf/DesKey.xml";
   // InputStream is =
   // DesUtil.class.getClassLoader().getResourceAsStream(keyFile);
   InputStream is = new FileInputStream(keyFile);
   ObjectInputStream oos = new ObjectInputStream(is);
   kp = (SecretKey) oos.readObject();
   oos.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return kp;
 }

 /**
  * 根据字符串得到key
  *
  * @param strKey
  *            密钥明文
  */
 public void getKey(String strKey) {
  try {
   KeyGenerator _generator = KeyGenerator.getInstance("DES");
   _generator.init(new SecureRandom(strKey.getBytes()));
   Key key = _generator.generateKey();
   _generator = null;
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static Properties getProperties() {
  Properties property = new Properties();
  // InputStream in = ClassLoader
  // .getSystemResourceAsStream("socket_jdbc.properties");
  InputStream in = MainEncrypt.class.getClassLoader()
    .getResourceAsStream("socket_jdbc.properties");

  try {
   property.load(in);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return property;
 }

 public MainEncrypt() {

  // SecretKey key = KeyUtil.getKey();
  SecretKey key = getKey();
  byte[] iv = new byte[] { (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07,
    0x72, 0x6F, 0x5A };
  AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
  try {
   ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

   // CBC requires an initialization vector
   ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
   dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
  } catch (java.security.InvalidAlgorithmParameterException e) {
  } catch (javax.crypto.NoSuchPaddingException e) {
  } catch (java.security.NoSuchAlgorithmException e) {
  } catch (java.security.InvalidKeyException e) {
  }
 }

 public byte[] getBytes(InputStream is) throws Exception {
  byte[] data = null;

  Collection chunks = new ArrayList();
  byte[] buffer = new byte[1024 * 1000];
  int read = -1;
  int size = 0;

  while ((read = is.read(buffer)) != -1) {
   if (read > 0) {
    byte[] chunk = new byte[read];
    System.arraycopy(buffer, 0, chunk, 0, read);
    chunks.add(chunk);
    size += chunk.length;
   }
  }

  if (size > 0) {
   ByteArrayOutputStream bos = null;
   try {
    bos = new ByteArrayOutputStream(size);
    for (Iterator itr = chunks.iterator(); itr.hasNext();) {
     byte[] chunk = (byte[]) itr.next();
     bos.write(chunk);
    }
    data = bos.toByteArray();
   } finally {
    if (bos != null) {
     bos.close();
    }
   }
  }
  return data;
 }

 /**
  * 加密String明文输入,String密文输出
  *
  * @param strMing
  * @return
  */
 public String getEncString(String strMing) {
  if (strMing == null) {
   strMing = "";
  }
  byte[] byteMi = null;
  byte[] byteMing = null;
  String strMi = "";
  BASE64Encoder base64en = new BASE64Encoder();
  try {
   byteMing = strMing.getBytes("UTF8");
   byteMi = this.getEncCode(byteMing);
   strMi = base64en.encode(byteMi);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   base64en = null;
   byteMing = null;
   byteMi = null;
  }
  return strMi;
 }

 /**
  * 解密 以String密文输入,String明文输出
  *
  * @param strMi
  * @return
  */
 public String getDesString(String strMi) {
  // byte[] byteMi = null;
  // String strMing = "";
  // ByteArrayOutputStream baos = new ByteArrayOutputStream();
  // 
  // try {
  // byteMi = strMi.getBytes("UTF8");
  //   
  // this.decrypt(new ByteArrayInputStream(byteMi), baos);
  // strMing = new String(baos.toByteArray());
  // } catch (Exception e) {
  // e.printStackTrace();
  // } finally {
  // }
  // return strMing;
  BASE64Decoder base64De = new BASE64Decoder();
  byte[] byteMing = null;
  byte[] byteMi = null;
  String strMing = "";
  try {
   byteMi = base64De.decodeBuffer(strMi);
   byteMing = this.getDesCode(byteMi);
   strMing = new String(byteMing, "UTF8");
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   base64De = null;
   byteMing = null;
   byteMi = null;
  }
  return strMing;
 }

 /**
  * 加密以byte[]明文输入,byte[]密文输出
  *
  * @param byteS
  * @return
  */
 public byte[] getEncCode(byte[] byteS) {
  byte[] byteFina = null;
  Cipher cipher;
  try {
   // cipher = Cipher.getInstance("DES");
   // cipher.init(Cipher.ENCRYPT_MODE, key,);
   // byteFina = cipher.doFinal(byteS);
   byteFina = ecipher.doFinal(byteS);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   cipher = null;
  }
  return byteFina;
 }

 /**
  * 解密以byte[]密文输入,以byte[]明文输出
  *
  * @param byteD
  * @return
  */
 public byte[] getDesCode(byte[] byteD) {
  Cipher cipher;
  byte[] byteFina = null;
  try {
   // cipher = Cipher.getInstance("DES");
   // cipher.init(Cipher.DECRYPT_MODE, key);
   // byteFina = cipher.doFinal(byteD);
   byteFina = dcipher.doFinal(byteD);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   cipher = null;
  }
  return byteFina;

 }

 // Buffer used to transport the bytes from one stream to another
 byte[] buf = new byte[1024];

 public void encrypt(InputStream in, OutputStream out) {
  try {
   // Bytes written to out will be encrypted
   out = new CipherOutputStream(out, ecipher);

   // Read in the cleartext bytes and write to out to encrypt
   int numRead = 0;
   while ((numRead = in.read(buf)) >= 0) {
    out.write(buf, 0, numRead);
   }

   // 关闭流在外面进行。
   // out.close();
  } catch (java.io.IOException e) {
  }
 }

 public void decrypt(InputStream in, OutputStream out) {
  try {
   // Bytes read from in will be decrypted
   in = new CipherInputStream(in, dcipher);

   // Read in the decrypted bytes and write the cleartext to out
   int numRead = 0;
   while ((numRead = in.read(buf)) >= 0) {
    out.write(buf, 0, numRead);
   }
   // out.flush();
   // 关闭流在外面进行。
   // out.close();
  } catch (java.io.IOException e) {
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  try {

   MainEncrypt encrypter = new MainEncrypt();

   // Encrypt
//    encrypter.encrypt(new FileInputStream("c:/photo.jpg"),
//     new FileOutputStream("c:/photo_enc.jpg"));
   // Decrypt
   encrypter.decrypt(new FileInputStream("c:/photo_enc.jpg"),
     new FileOutputStream("c:/photo_des.jpg"));

  } catch (Exception e) {
   e.printStackTrace();
  }

 }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值