import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Scanner;
import sun.misc.BASE64Encoder;
public class DES {
public static final String ALGORITHM="DES";
public static void main(String[] args) {
String str = null;
Scanner scanner = new Scanner(System.in);
str = scanner.next();
System.out.println("原文:"+str);
// 加密和解密
try {
Key key = toKey();
System.out.println("密钥:"+key);
byte[] encrytoResult = encrypt(str.getBytes(), key);
BASE64Encoder base64Encoder = new BASE64Encoder(); //将字节转换为字符串输出
System.out.println("加密后:"+base64Encoder.encode(encrytoResult));
byte[] decrytoResult = decrypt(encrytoResult,key);
System.out.println("解密后:"+new String(decrytoResult));
}catch (Exception e){
e.printStackTrace();
}
}
// 生成密钥
public static Key toKey() throws Exception{
// DESKeySpec desKeySpec = new DESKeySpec(key);
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// secretKey = keyFactory.generateSecret(desKeySpec);
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(56);//密钥长度为64位
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
}
//加密
public static byte[] encrypt(byte[] data,Key key) throws Exception{
SecureRandom random = new SecureRandom();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, random);
return cipher.doFinal(data);
}
// 解密
public static byte[] decrypt(byte[] data,Key key) throws Exception{
SecureRandom random = new SecureRandom();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE,key,random);
return cipher.doFinal(data);
}
}
遇到的问题:sun.misc.BASE64Encoder找不到jar包?
解决方法:右击项目->properties->java build path,将JRE System Library先移除,再将JRE System Library加进来,重新编译一下就行了。