在Java中,加密和解密密码通常使用Java Cryptography Extension (JCE) 和 Java Cryptography Architecture (JCA)。JCE和JCA是Java平台的标准扩展,提供了一系列加密算法和相关服务。
以下是使用Java加密和解密密码的一些建议:
以下是一个使用AES加密和解密密码的示例:
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.util.Base64;
public class AESDemo {
private static final byte[] KEY_BYTES = new byte[16]; // 128-bit key
public static void main(String[] args) {
String plaintext = "Hello, world!";
String encrypted = encrypt(plaintext);
String decrypted = decrypt(encrypted);
System.out.println("Plaintext: " + plaintext);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
}
public static String encrypt(String plaintext) {
try {
SecretKeySpec keySpec = new SecretKeySpec(KEY_BYTES, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(iv) + ":" + Base64.getEncoder().encodeToString(ciphertext);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String decrypt(String ciphertext) {
try {
String[] parts = ciphertext.split(":");
byte[] iv = Base64.getDecoder().decode(parts[0]);
byte[] encrypted = Base64.getDecoder().decode(parts[1]);
SecretKeySpec keySpec = new SecretKeySpec(KEY_BYTES, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
byte[] plaintext = cipher.doFinal(encrypted);
return new String(plaintext);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
请注意,此示例仅用于演示目的。在实际应用中,您需要确保使用更强大的加密算法(如RSA)和更安全的密钥管理策略。
领取专属 10元无门槛券
手把手带您无忧上云