DES加密--从文件中读取需要加密的文件
编程要求:
需要从文件中读出需要加密的内容
使用DES加密后,将加密后的内容存入文件中
密钥使用学号
源码如下
DESdemo
.
package desserect;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
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.DESKeySpec;
public class DESdemo {
//KeyGenerator 提供对称密钥生成器的功能,支持各种算法
private KeyGenerator keygen;
//SecretKey 负责保存对称密钥
private SecretKey deskey;
private SecretKey mykey;
//Cipher负责完成加密或解密工作
private Cipher c;
//该字节数组负责保存加密的结果
private byte[] cipherByte;
/**
* 辅助方法,字节数组转16进制
* @param bytes 需要转换的byte数组
* @return 转换后的Hex字符串
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
sb.append(" ");//每个十六进制之间加入一个空格
}
return sb.toString();
}
public DESdemo() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException{
//方法1 自动产生密码
//实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
keygen = KeyGenerator.getInstance("DES");
//生成密钥
deskey = keygen.generateKey();
//获取密码的字符数组
byte[] encodedKey = deskey.getEncoded();
//生成key的字符串
System.out.println("DES Key is: "+ bytesToHex(encodedKey));
//方法2 指定密钥进行加解密
//byte[] password = {'a','b','c','d','e','f','g','h'};//指定密码为abcdefgh
byte[] password = "2018212176".getBytes();
DESKeySpec keySpec = new DESKeySpec(password);
//转成des key对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
mykey = keyFactory.generateSecret(keySpec);
//打印手工设置的key
byte[] myEncodedKey = mykey.getEncoded();
System.out.println("My Key is: "+ bytesToHex(myEncodedKey));
//生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("DES");
}
/**
* 对字符串加密
*
* @param str
* @return
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public byte[] Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
c.init(Cipher.ENCRYPT_MODE, mykey);
// 输入的是字符串,先转成对应的byte数组
byte[] src = str.getBytes();
// 加密,结果保存进cipherByte
cipherByte = c.doFinal(src);
return cipherByte;
}
/**
* 对字符串解密
*
* @param buff
* @return
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
c.init(Cipher.DECRYPT_MODE, mykey);
cipherByte = c.doFinal(buff);
return cipherByte;
}
/**
* @param args
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidKeyException
*/
public static void main(String[] args) throws Exception {
DESdemo de1 = new DESdemo();
String msg ="this is DES example.";
byte[] encontent = de1.Encrytor(msg);
byte[] decontent = de1.Decryptor(encontent);
System.out.println("明文是:" + msg);
System.out.println("加密后:" + new String(encontent));
System.out.println("解密后:" + new String(decontent));
}
}
Test
package desserect;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class Test {
//read file
public String readFile(String url) {
try {
File f=new File(url);
if(f.isFile()&&f.exists())
{
InputStreamReader reader=new InputStreamReader(new FileInputStream(f),"utf-8");
BufferedReader br=new BufferedReader(reader);
String line;
while((line=br.readLine())!=null){
return line;
}
reader.close();
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
//save file
public void saveFile(String s,String url) throws IOException {
File f =new File(url);
if(!f.exists()) {
f.createNewFile();
}
OutputStreamWriter write=new OutputStreamWriter(new FileOutputStream(f),"utf-8");
BufferedWriter writer=new BufferedWriter(write);
writer.write(s);
System.out.println("successful");
writer.close();
}
public static void main(String[] args) throws Exception {
Test s1=new Test();
DESdemo des1=new DESdemo();
//将需要加密文本的内容从文件LqqAddress.txt文本中读出来,并存入临时变量msg中
String msg=s1.readFile("d:/LqqAddress.txt");
System.out.println("读出的信息是:"+msg);
//使用DES算法对文件内容进行加密
byte[] encontent = des1.Encrytor(msg);
System.out.println("加密后:" + new String(encontent));
//将用des加密后的文件存入到LqqAddressSerect.txt文件中
String s=new String(encontent);
s1.saveFile(s, "d:/LqqAddressSerect.txt");
}
}