AES-256是一种高级加密标准,它使用256位密钥对数据进行加密和解密。下面是一个使用Java编程语言实现AES-256加密和解密的示例代码:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AES {
private static final String ALGORITHM = "AES";
private static final String ENCRYPTION_KEY = "YOUR_ENCRYPTION_KEY";
public static String encrypt(String plainText) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String encryptedText = encrypt(plainText);
String decryptedText = decrypt(encryptedText);
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}
在上面的示例代码中,ENCRYPTION_KEY
变量是用于加密和解密的密钥。请将其替换为您自己的密钥。在main
方法中,我们将一个字符串进行加密,并将加密后的结果解密回来,然后打印出来。
请注意,这只是一个简单的示例,实际使用时,您可能需要添加更多的错误处理和安全措施。