import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class PwdUtils {
private static final Pattern SPECIAL_CHAR_PATTERN = Pattern.compile("[.!@#$%^&*()_+{}\":<>?]");
private static final Logger log = LoggerFactory.getLogger(PwdUtils.class);
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
private static final String SALT = "16位秘钥";
// 密码加密
public static String encrypt(String password) throws Exception {
byte[] keyBytes = SALT.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(password.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 密码解密
public static String decrypt(String encryptedPassword) throws Exception {
byte[] keyBytes = SALT.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedPassword);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
// 测试
public static void main(String[] args) throws Exception {
String password = "22222!";
String encryptedPassword = encrypt(password);
System.out.println("Encrypted Password: " + encryptedPassword);
String decryptedPassword = decrypt(encryptedPassword);
System.out.println("Decrypted Password: " + decryptedPassword);
}
}
为什么不用256呢?
解除限制太麻烦了