之前写过一个,但是相比只下这个类可以直接放到方法当中使用,加密文件,可以生成出来,而不是像我这样
当然,主要是针对文字的加密。
上代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Des {
public static void main(String[] args) {
createKey(); //生成密钥
System.out.println(new String(
decrypt( //解密
encrypt("你好!")))); //加密
}
/**
* 生成密钥,保存到文件当中
*/
private static void createKey(){
try {
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56);
SecretKey sk = kg.generateKey();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("c://test.key")));
oos.writeObject(sk);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 读取密钥
* @return Key
*/
private static Key getKey(String filePath){
Key key = null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(filePath)));
key = (Key)ois.readObject();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return key;
}
/**
* 加密
* @param cipherText
* @return
*/
private static byte[] encrypt(String cipherText) {
byte[] targer = null;
try {
byte[] text = cipherText.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, getKey("c://test.key"));
targer = cipher.doFinal(text);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return targer;
}
/**
* 解密
* @param cipherText
* @return
*/
private static byte[] decrypt(byte[] cipherText){
byte[] decryptText = null;
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, getKey("c://test.key"));
decryptText = cipher.doFinal(cipherText);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return decryptText;
}
}
接下来研究3des