`
jameszhao83
  • 浏览: 66039 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

java AES加密

阅读更多
package com.james.chps;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class CephTest {

	/**
	 * @param args
	 * @throws Exception 
	 * @throws NoSuchAlgorithmException 
	 */
	public static void main(String[] args) throws NoSuchAlgorithmException, Exception {
		// TODO Auto-generated method stub
       Cipher c=Cipher.getInstance("AES");
       FileInputStream fis=new FileInputStream("myscret.key");
       ObjectInputStream ois=new ObjectInputStream(fis);
       Key key=(Key) ois.readObject();
       //SecretKey sk=KeyGenerator.getInstance("AES").generateKey();
      //加密
       c.init(Cipher.ENCRYPT_MODE, key);
      //从加密文件中读出key

       byte[] jiamihou=c.doFinal("sdfa".getBytes());
       System.out.println(jiamihou);
       //解密
       c.init(Cipher.DECRYPT_MODE, key);
       System.out.println(new String(c.doFinal(jiamihou)));
	}
	
	//method1
	public void method1() throws Exception, Throwable{
		// TODO Auto-generated method stub
	       Cipher c=Cipher.getInstance("AES");
	       SecretKey sk=KeyGenerator.getInstance("AES").generateKey();
	      //加密
	       c.init(Cipher.ENCRYPT_MODE, sk);

	       byte[] jiamihou=c.doFinal("sdfa".getBytes());
	       System.out.println(jiamihou);
	       //解密
	       c.init(Cipher.DECRYPT_MODE, sk);
	       System.out.println(new String(c.doFinal(jiamihou)));
	}
    //method2将密匙写入文件
	public void method3() throws Exception{
		// TODO Auto-generated method stub
	       Cipher c=Cipher.getInstance("AES");
	       SecretKey sk=KeyGenerator.getInstance("AES").generateKey();
	      //加密
	       c.init(Cipher.ENCRYPT_MODE, sk);
	      //密匙写入文件
	       FileOutputStream fos=new FileOutputStream("myscret.key");
	       ObjectOutputStream oos=new ObjectOutputStream(fos);
	       oos.writeObject(sk);
	       oos.flush();
	       oos.close();
	       byte[] jiamihou=c.doFinal("sdfa".getBytes());
	       System.out.println(jiamihou);
	       //解密
	       c.init(Cipher.DECRYPT_MODE, sk);
	       System.out.println(new String(c.doFinal(jiamihou)));
	}
}
 
分享到:
评论
1 楼 zhengyong7232 2013-04-23  
请问 myscret.key 怎么产生的啊?

相关推荐

Global site tag (gtag.js) - Google Analytics