使用密码来加密解密


package com.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

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 Exception
{
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

SecretKey key2 = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("123456789".toCharArray()));
PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8},100);
//加密
cipher.init(Cipher.ENCRYPT_MODE, key2, parameterSpec);

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

OutputStream 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 Exception
{
//解密
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

SecretKey key2 = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("123456789".toCharArray()));
PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8},100);
cipher.init(Cipher.DECRYPT_MODE, key2,parameterSpec);

InputStream 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();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值