0% found this document useful (0 votes)
48 views2 pages

Java AES Encryption Example

This Java code sample demonstrates how to encrypt and decrypt a string using AES symmetric encryption. It generates an AES secret key, uses it to encrypt a message into bytes, then decrypts the bytes back into the original string. The encrypted and original bytes are also printed as hexadecimal strings for viewing.

Uploaded by

rajubomma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views2 pages

Java AES Encryption Example

This Java code sample demonstrates how to encrypt and decrypt a string using AES symmetric encryption. It generates an AES secret key, uses it to encrypt a message into bytes, then decrypts the bytes back into the original string. The encrypted and original bytes are also printed as hexadecimal strings for viewing.

Uploaded by

rajubomma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.security.

*;
import javax.crypto.*;
import
javax.crypto.spec.*;
import java.io.*;
public class AES {
public static String asHex (byte buf[]) {

StringBuffer strbuf = new StringBuffer(buf.length*2);

int i;
for (i = 0; i < buf.length; i++)
{
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
} return strbuf.toString(); }
public static void main(String[] args) throws Exception
{ String message="AES still rocks!!";
/ / Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); / / 192 and 256 bits may not be availab le
/ / Generate the secret key specs.
SecretKey skey =
kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
/ / Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((args.length == 0 ? message :

args[0]).getBytes()); System.out.println("encrypted string: " +


asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " +originalString + " " + asHex(original));
}
}

You might also like