在Java中,有多种方法可以对字符串进行加密。以下是一些常用的加密算法:
javax.crypto
库进行AES加密的示例:import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String key = "ThisIsASecretKey"; // 16, 24或32个字符
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted Text: " + encryptedText);
}
}
注意:在实际应用中,不建议使用硬编码的密钥,而应该将其安全地存储和管理。
javax.crypto
库进行RSA加密的示例:import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted Text: " + encryptedText);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedBytes);
System.out.println("Decrypted Text: " + decryptedText);
}
}
同样,在实际应用中,不建议使用硬编码的密钥,而应该将其安全地存储和管理。
以上示例仅用于演示目的,实际应用中可能需要根据具体需求进行调整和优化。在选择加密算法时,请确保选择适合您需求的算法,并遵循最佳实践来保护您的数据和系统安全。