You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.1 KiB
73 lines
2.1 KiB
package wusthelper.web.util;
|
|
|
|
import cn.hutool.core.util.HexUtil;
|
|
import cn.hutool.crypto.Mode;
|
|
import cn.hutool.crypto.Padding;
|
|
import cn.hutool.crypto.symmetric.AES;
|
|
import cn.hutool.crypto.symmetric.SymmetricCrypto;
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.util.StringJoiner;
|
|
|
|
/**
|
|
* 密码编解码器,
|
|
* 用aes加密而不是常规密码存储使用的hash摘要,是因为有获取明文密码的需求,毕竟登录进系统还是要明文密码的,
|
|
* 日后如果将数据获取转到客户端上进行,可以改为bcrypt存储
|
|
*/
|
|
public class PasswordCodec {
|
|
|
|
private final SymmetricCrypto aes;
|
|
|
|
public PasswordCodec(String key) {
|
|
byte[] keyBytes = normalization(key);
|
|
this.aes = new AES(Mode.ECB, Padding.PKCS5Padding, keyBytes);
|
|
}
|
|
|
|
public PasswordCodec(byte[] key) {
|
|
this.aes = new AES(Mode.ECB, Padding.PKCS5Padding, key);
|
|
}
|
|
|
|
private static byte[] normalization(String key) {
|
|
if (key.length() < 16) {
|
|
StringJoiner sj = new StringJoiner(key);
|
|
for (int i = 0; i < 16 - key.length(); i++) {
|
|
sj.add("a");
|
|
}
|
|
key = sj.toString();
|
|
} else if (key.length() > 16) {
|
|
key = key.substring(15);
|
|
}
|
|
|
|
return key.getBytes(StandardCharsets.UTF_8);
|
|
}
|
|
|
|
public String encode(String raw) {
|
|
if (raw == null) {
|
|
return null;
|
|
}
|
|
|
|
byte[] data = aes.encrypt(raw.getBytes(StandardCharsets.UTF_8));
|
|
return HexUtil.encodeHexStr(data);
|
|
}
|
|
|
|
public String decode(String encodedHex) {
|
|
if (encodedHex == null) {
|
|
return null;
|
|
}
|
|
|
|
byte[] data = aes.decrypt(HexUtil.decodeHex(encodedHex));
|
|
return new String(data);
|
|
}
|
|
//
|
|
// public static PasswordUtil getInstance(String key) {
|
|
// if (instance == null) {
|
|
// synchronized (PasswordUtil.class) {
|
|
// if (instance == null) {
|
|
// instance = new PasswordUtil(key);
|
|
// }
|
|
// }
|
|
// }
|
|
//
|
|
// return instance;
|
|
// }
|
|
}
|
|
|