import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;
/**
* 3DES加密
*
* @author hcf
* @date 2021/9/1 20:56
*/
@Slf4j
public class DES3Utils {
/**
* 向量
*/
private final static String IV = "01234567";
private static final String ALGORITHM = "DESede";
private static final String ALGORITHM_NAME = "DESede/CBC/PKCS5Padding";
/**
* 加密
*
* @param hexKey 密钥
* @param content 内容
* @return 密文
*/
public static String encrypt(String hexKey, String content) {
String encryptContent = StringUtils.EMPTY;
try {
DESedeKeySpec spec = new DESedeKeySpec(hexKey.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
Key key = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, key, ips);
byte[] encryptData = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
encryptContent = Base64.getEncoder().encodeToString(encryptData);
} catch (Exception e) {
log.error(" DES3Utils.encrypt error {}", e.getMessage(), e);
}
return encryptContent;
}
/**
* 解密
*
* @param hexKey 明文密钥
* @param encryptContent 加密内容
* @return 明文
*/
public static String decrypt(String hexKey, String encryptContent) {
String content = StringUtils.EMPTY;
try {
DESedeKeySpec spec = new DESedeKeySpec(hexKey.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
Key key = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, key, ips);
byte[] decryptData = cipher.doFinal(Base64.getDecoder().decode(encryptContent));
content = new String(decryptData, StandardCharsets.UTF_8);
} catch (Exception e) {
log.error(" DES3Utils.decrypt error {}", e.getMessage(), e);
}
return content;
}
public static void main(String[] args) {
String hexCipher = CipherUtils.randomHexCipher();
String encrypt = encrypt(hexCipher, "content");
System.out.println(encrypt);
System.out.println(decrypt(hexCipher, encrypt));
}
}
CipherUtils 参照