Skip to content

Instantly share code, notes, and snippets.

@manjula-aw
Created October 8, 2010 15:25
Show Gist options
  • Save manjula-aw/616966 to your computer and use it in GitHub Desktop.
Save manjula-aw/616966 to your computer and use it in GitHub Desktop.
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Class for encrypting/decrypting texts using AES encryption
* @author Manjula AW
*/
public class AESEncryption {
public static void main(String[] args) throws Exception {
String messageToEncrypt = "test";
System.out.println("Message to encrypt: " + messageToEncrypt);
// KeyGenerator keygen = KeyGenerator.getInstance("AES");
// keygen.init(128);
// SecretKey skey = keygen.generateKey();
// byte[] encKey = skey.getEncoded();
byte[] encKey = new byte[]{-32, 74, 61, 28, -125, 118, -124, 85, 37, -23, 88, 110, 32, -76, -55, 74};
String encrypted = encrypt(messageToEncrypt, encKey);
System.out.println("Encrypted string: " + encrypted);
String originalString = decrypt(encrypted, encKey);
System.out.println("Original string: " + originalString);
}
/**
* Encrypt given string <code>plainText</code> in AES encryption using the given key <code>rawkey</code>.
* @param plainText string to be decrypted
* @param rawkey encryption key
* @return encrypted string
* @throws Exception
*/
public static String encrypt(String plainText, byte[] rawkey) throws Exception {
try {
SecretKeySpec skeySpec = new SecretKeySpec(rawkey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((new BASE64Decoder()).decodeBuffer(plainText));
return (new BASE64Encoder()).encode(encrypted);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
throw e;
}
}
/**
* Decrypt given AES encrypted string <code>encryptedText</code> using given key <code>rawkey</code>
* @param encryptedText string to be decrypted
* @param rawkey decryption key (same encryption key used to encrypt this text)
* @return decrypted string
* @throws Exception
*/
public static String decrypt(String encryptedText, byte[] rawkey) throws Exception {
try {
SecretKeySpec skeySpec = new SecretKeySpec(rawkey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal((new BASE64Decoder()).decodeBuffer(encryptedText));
return (new BASE64Encoder()).encode(decrypted);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
throw e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment