java AES encrypt and decrypt
javaIn Java, you can use the Cipher class from the javax.crypto package to perform AES encryption and decryption. Here’s an example of how you can use the Cipher class to encrypt and decrypt a message in Java:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
// Set up the Cipher object
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// Create a secret key
byte[] keyBytes = "0123456789012345".getBytes("UTF-8");
Key key = new SecretKeySpec(keyBytes, "AES");
// Encrypt the message
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal("Hello, world!".getBytes("UTF-8"));
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println(encryptedString);
// Decrypt the message
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
String decryptedString = new String(decryptedBytes, "UTF-8");
System.out.println(decryptedString);
}
}
This code will output the encrypted version of the message “Hello, world!” and then output the decrypted version of the same message.
Note that in this example, the secret key is a simple string that is used as the key for the AES algorithm. In a real application, you should use a more secure key, such as one that is generated using a key derivation function like PBKDF2.
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java