import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class PasswordEncryptor {
public static String encrypt(String password, String secretKey) throws Exception {
// 创建AES加密器
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// 加密密码
byte[] encryptedBytes = cipher.doFinal(password.getBytes("UTF-8"));
// 使用Base64编码加密后的密码
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedPassword, String secretKey) throws Exception {
// 创建AES解密器
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
// 使用Base64解码加密后的密码
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedPassword);
// 解密密码
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, "UTF-8");
}
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: PasswordEncryptor <encrypt/decrypt> <password> <secretKey>");
System.exit(1);
}
String mode = args[0];
String password = args[1];
String secretKey = args[2];
if ("encrypt".equals(mode)) {
String encryptedPassword = encrypt(password, secretKey);
System.out.println("Encrypted Password: " + encryptedPassword);
} else if ("decrypt".equals(mode)) {
String decryptedPassword = decrypt(password, secretKey);
System.out.println("Decrypted Password: " + decryptedPassword);
} else {
System.err.println("Invalid mode. Use 'encrypt' or 'decrypt'.");
System.exit(1);
}
}
}