I have this simple code, that i found on the internet.. im learning this stuff of encryption/decryption.. this code seems to work fine, but i don't understand something... why after the "c.doFinal()" (which is for encrypt/decrypt with AES-256) this guy encode/decode that encrypted value, with BASE64? its not enough only by using AES?
`private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
public static void main(String[] args) throws Exception {
String data = "SOME TEXT";
String dataEnc = AES.encrypt(data);
String dataDec = AES.decrypt(dataEnc);
System.out.println("Plain Text : " + data);
System.out.println("Encrypted Text : " + dataEnc);
System.out.println("Decrypted Text : " + dataDec);
}`
Thanks!!
Here padding is required and Java provides 3 alternatives. For encoding, the AES algorithm is repetitive in nature and supports 128, 192, and 256 bits.
AES, Advanced Encryption Standard is a block ciphertext encryption and decryption algorithm that processes a block of 128 bits of data using secret keys of 128, 192, or 256 bits. We will also discuss how this algorithm can be implemented using the Java programming language.
Out of 128-bit, 192-bit, and 256-bit AES encryption, 256-bit AES encryption is technically the most secure because of its key length size. Some go as far as to label 256-bit AES encryption overkill because it, based on some estimations, would take trillions of years to crack using a brute-force attack.
The Advanced Encryption Standard (AES) is a widely used symmetric-key encryption algorithm.
The encrypted data returned by doFinal
is binary, and so it cannot be printed (it'll appear as a bunch of gibberish.) The Base64 encoding converts the binary to a set of ASCII characters, this makes it easily readable and also makes it possible to use the encrypted data in situations where only plaintext data can be used.
The Base64 encoding doesn't add any extra encryption or security, it simply makes the encrypted data usable in situations where you can't use binary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With