网上看到的都是用了第三方包的,我这里写了个纯java无依赖的
环境
- JDK11
- Windows7
- VS Code
代码
源代码都发布在Gitee上了
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
public class DES {
private static final byte[] DESIV = { (byte) 0xCE, (byte) 0x35, (byte) 0x5,
(byte) 0xD, (byte) 0x98, (byte) 0x91, (byte) 0x8, (byte) 0xA };
private static AlgorithmParameterSpec IV = null;
private static final int ENCRYPT_MODE = 1;
private static final int DECRYPT_MODE = 2;
private Key key;
public DES(String str) {
getKey(str);
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public void getKey(String secretKey) {
try {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(secretKey.getBytes());
KeyGenerator generator = null;
try {
generator = KeyGenerator.getInstance("DES");
} catch (NoSuchAlgorithmException e) {
}
generator.init(secureRandom);
IV = new IvParameterSpec(DESIV);
this.key = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException("Error in getKey(String secretKey), Cause: " + e);
}
}
public byte[] encrypt(byte[] data) throws Exception {
Cipher cipher = getPattern(ENCRYPT_MODE);
return cipher.doFinal(data);
}
public byte[] decrypt(byte[] data) throws Exception {
Cipher cipher = getPattern(DECRYPT_MODE);
return cipher.doFinal(data);
}
private Cipher getPattern(int cipherMode) throws Exception {
Cipher cipher;
cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(cipherMode, key, IV);
return cipher;
}
public static void main(String[] args) throws Exception {
String testString = "I am YiMi";
DES des = new DES("blockchain");
String stringMi = Base64.getEncoder().encodeToString(des.encrypt(testString.getBytes()));
System.out.println("密文:" + stringMi);
byte[] stringMing = des.decrypt(Base64.getDecoder().decode(stringMi));
System.out.println("明文:" + new String(stringMing));
}
}