一、 DesCbcComponent
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class DesCbcComponent {
private SecretKey key;
public SecretKey getKey() {
return key;
}
public DesCbcComponent(String key) {
setKey(key);
}
private void setKey(String key) {
byte[] bytes = new byte[8];
byte[] userInput = key.getBytes();
for (int i = 0;i<8 && i < userInput.length; i++) {
bytes[i] = userInput[i];
}
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpec = new DESKeySpec(bytes);
this.key = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
}
public String enCrypt(String plainText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
desCipher.init(Cipher.ENCRYPT_MODE, this.key,iv);
byte[] bytes = desCipher.doFinal(plainText.getBytes());
return encodeTo64(bytes);
}
public String deCrypt(String base64Str) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
byte[] cipherText = decodeFrom64(base64Str);
Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
desCipher.init(Cipher.DECRYPT_MODE, this.key,iv);
byte[] textDecrypted = desCipher.doFinal(cipherText);
return new String(textDecrypted);
}
private static String encodeTo64(byte[] src){
Base64.Encoder encoder = Base64.getEncoder();
return new String(encoder.encode(src));
}
private static byte[] decodeFrom64(String from){
Base64.Decoder decoder = Base64.getDecoder();
return decoder.decode(from);
}
}
二、DesCbcComponentTest
public class DesCbcComponentTest {
public static void main(String[] args) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
DesCbcComponent desComponent = new DesCbcComponent("kesa");
String plainText="don't stop!!!";
String base64Cipher = desComponent.enCrypt(plainText);
System.out.println("base64密文 : "+base64Cipher);
String plainText2 = desComponent.deCrypt(base64Cipher);
System.out.println("GBK原文 : " + plainText2);
}
}
--------------------------------------------------------------------------------------------------------
console:
base64密文 : b6I8AlbDPeEA3ZFdx/4kdw==
GBK原文 : don't stop!!!