2023-08-21 08:14:20
浏览数 (1)
POM.XML配置
代码语言:javascript
复制<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shouke</groupId>
<artifactId>des-utils</artifactId>
<version>1.0</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies>
</project>
代码实现
代码语言:javascript
复制package com.shouke.utils;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
/**
* @description:对称加密
*/
public class DesUtil {
private static final String KEY = "jPQQqFT3lwg=";
/**
* 根据KEY生成DES
*/
private static final DES DES = SecureUtil.des(SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), KEY.getBytes()).getEncoded());
/**
* 获取加密后信息
*
* @param plainText 明文
* @return 加密后信息
*/
public static String getEncryptData(String plainText) {
return DES.encryptHex(plainText); // 加密为16进制
}
/**
* 获取解密后信息
*
* @param cipherText 密文
* @return 解密后信息
*/
public static String getDecryptData(String cipherText) {
return DES.decryptStr(cipherText);
}
/**
* 生成密钥,并转为字符串,可以储存起来,解密时可直接使用
*
* @return 密钥
*/
public static String getSecretKey() {
byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue()).getEncoded(); // 随机生成秘钥
return Base64.encode(key);
}
public static void main(String[] args) {
System.out.println(getEncryptData("shouke")); // 输出:21e995a30ccbfa38
}
}