Cipher加密解密


package com.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class CipherTest
{

public static void main(String[] args)
{
try
{
//secretEncrypt();


secretDecrypt();


}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private static void secretEncrypt() throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, FileNotFoundException,
IOException, IllegalBlockSizeException, BadPaddingException
{
Cipher cipher = Cipher.getInstance("AES");
SecretKey key = KeyGenerator.getInstance("AES").generateKey();

//加密
cipher.init(Cipher.ENCRYPT_MODE, key);

OutputStream os = new FileOutputStream("secret_key");
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(key);
oos.close();
os.close();

byte[] result = cipher.doFinal("aab".getBytes());

os = new FileOutputStream("secret_data");
BufferedOutputStream bos = new BufferedOutputStream(os);
bos.write(result);
bos.close();
os.close();

System.out.println(new String(result));
}

private static void secretDecrypt() throws NoSuchAlgorithmException,
NoSuchPaddingException, FileNotFoundException, IOException,
ClassNotFoundException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException
{
//解密
Cipher cipher = Cipher.getInstance("AES");

InputStream is = new FileInputStream("secret_key");
ObjectInputStream ois = new ObjectInputStream(is);
SecretKey key = (SecretKey)ois.readObject();
ois.close();
is.close();

cipher.init(Cipher.DECRYPT_MODE, key);

is = new FileInputStream("secret_data");
BufferedInputStream bis = new BufferedInputStream(is);

// ByteArrayOutputStream baos = new ByteArrayOutputStream();

//方法一:
// byte[] rs = new byte[1024];
// int length = 0;
// while((length = bis.read(rs)) != -1){
// baos.write(rs, 0, length);
// }

//方法二:
byte[] rs = new byte[bis.available()];
int length = bis.read(rs);
int total = 0;
while(total < bis.available()){
total += length;

length = bis.read(rs, total, bis.available() - total);
}

//System.out.println(new String(cipher.doFinal(baos.toByteArray())));
System.out.println(new String(cipher.doFinal(rs)));
// baos.close();
bis.close();
is.close();
}

}

展开阅读全文

没有更多推荐了,返回首页