DESede加密

package DES;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class DES_Encrypt {

private String toPath = null; // 保存密钥路径
private SecretKey secretKey = null; // 密钥
private String encryptString = null; // 加密数据

/*
* 传递要加密的字符串,指定保存密钥的路径
*/
public byte [] encrypt(String encryptString ,String toPath) throws Exception {
panDuanToPath(new File(toPath));
getKeyGenerator();
this.encryptString = encryptString;
return encrypt();
}

/*
* 传递了要加密的ArrayList<String>,指定保存密钥路径
*/
public ArrayList<byte []> encrypt(ArrayList<String> list, String toPath) throws Exception {
ArrayList<byte []> listEncryptByte = new ArrayList<byte []> ();
panDuanToPath(new File(toPath));
getKeyGenerator();
for(String encryptString : list) {
this.encryptString = encryptString;
listEncryptByte.add(encrypt());
}
return listEncryptByte;
}
/*
* 传递要加密的String数组,指定保存密钥路径
*/
public ArrayList<byte []> encrypt(String [] str,String toPath) throws Exception {
ArrayList<byte []> listEncryptByte = new ArrayList<byte []> ();
panDuanToPath(new File(toPath));
getKeyGenerator();
for(String encryptString : str) {
this.encryptString = encryptString;
listEncryptByte.add(encrypt());
}
return listEncryptByte;

}

/*
* 判断保存路径
*/
private void panDuanToPath(File toPath) {
try {
if(!toPath.exists()) {
toPath.createNewFile();
}
this.toPath = toPath.getPath();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
/*
* 获取密钥.并保存到指定文件中
*/
private void getKeyGenerator() throws Exception {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
// 获取密钥生成器对象
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
// 密钥生成器初始化
keyGenerator.init(168);
// 取得用来加密的密钥
this.secretKey = keyGenerator.generateKey();
fos = new FileOutputStream(this.toPath);
oos = new ObjectOutputStream(fos);
oos.writeObject(secretKey);
oos.close();
fos.close();
}

/*
* 加密
*/
private byte [] encrypt() throws Exception {
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte [] encryptStringByte = cipher.doFinal(encryptString.getBytes());
print("DESede数据加密成功");
return encryptStringByte;
}

private void print(String value) {
System.out.println(value);
}

public static void main(String [] args) throws Exception {
DES_Encrypt des = new DES_Encrypt();
des.encrypt("dfasdf", "d:/list/ddd.txt");
ArrayList<String> list = new ArrayList<String> ();
list.add("wanglin");
list.add("wfambwl");
des.encrypt(list,"d:/list/txt.txt");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值