How to use Java to encrypt text
To encrypt text using Java, you can utilize the encryption class in the Java Encryption Standard library. Here is an example of encrypting text using the AES algorithm.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class TextEncryptionExample {
public static void main(String[] args) {
try {
// 生成AES密钥
SecretKey secretKey = generateAESKey();
// 明文
String plaintext = "Hello, World!";
// 加密
String ciphertext = encrypt(plaintext, secretKey);
System.out.println("密文: " + ciphertext);
// 解密
String decryptedText = decrypt(ciphertext, secretKey);
System.out.println("解密后的明文: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成AES密钥
public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();
}
// 加密
public static String encrypt(String plaintext, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密
public static String decrypt(String ciphertext, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
This example demonstrates the use of the AES algorithm for encrypting and decrypting text. Firstly, an AES key is generated using the generateAESKey() method. Next, the encrypt() method is used to encrypt the plaintext and return the encrypted ciphertext in Base64 encoding. Finally, the decrypt() method is used to decrypt the ciphertext and obtain the original plaintext.
Please note that this example is for demonstration purposes only and does not take into consideration security issues. In actual applications, it is necessary to choose the appropriate encryption algorithm and key length based on specific requirements, as well as implement adequate security measures.