AES Encryption & Decryption
Encrypt and decrypt text online with AES-128, AES-192 or AES-256. Free, no registration — runs right in your browser, fully compatible with the server-side AES.
What is AES encryption?
AES (Advanced Encryption Standard) is a symmetric encryption algorithm developed by the Belgian cryptographers Joan Daemen and Vincent Rijmen. It uses a 128-bit block length and supports key lengths of 128, 192 and 256 bits, and was designed to be efficient in both hardware and software. This page is a free web tool that encrypts and decrypts text with AES — the result is downloadable as a text file.
How to use this AES encryption tool
To encrypt: paste your text in the box above, set a secret key, choose the key size
and press Encrypt. The result appears Base64-encoded to avoid character-encoding problems.
To decrypt: make sure the text is Base64-encoded and was encrypted with AES, paste it
in the box, enter the same key and key size, then press Decrypt.
When is AES encryption helpful?
Whenever you want to turn confidential text into a decryptable format — for example, before sending sensitive data by e-mail. The encrypted text can only be decrypted by someone who knows the correct key.
How secure is AES encryption?
AES is approved by the U.S. government for securing sensitive information, so with a strong key it is considered very secure.
Implementation note (PHP 7.x)
This implementation uses openssl instead of the deprecated mcrypt.
Because of the different padding/IV handling, results from the two are not compatible with each other.
PHP AES encryption with openssl example.(versions 7.x)
/**
Aes encryption
*/
class AES {
protected $key;
protected $data;
protected $method;
/**
* Available OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
*
* @var type $options
*/
protected $options = 0;
/**
*
* @param type $data
* @param type $key
* @param type $blockSize
* @param type $mode
*/
function __construct($data = null, $key = null, $blockSize = null, $mode = 'CBC') {
$this->setData($data);
$this->setKey($key);
$this->setMethode($blockSize, $mode);
}
/**
*
* @param type $data
*/
public function setData($data) {
$this->data = $data;
}
/**
*
* @param type $key
*/
public function setKey($key) {
$this->key = $key;
}
/**
* CBC 128 192 256
CBC-HMAC-SHA1 128 256
CBC-HMAC-SHA256 128 256
CFB 128 192 256
CFB1 128 192 256
CFB8 128 192 256
CTR 128 192 256
ECB 128 192 256
OFB 128 192 256
XTS 128 256
* @param type $blockSize
* @param type $mode
*/
public function setMethode($blockSize, $mode = 'CBC') {
if($blockSize==192 && in_array('', array('CBC-HMAC-SHA1','CBC-HMAC-SHA256','XTS'))){
$this->method=null;
throw new Exception('Invlid block size and mode combination!');
}
$this->method = 'AES-' . $blockSize . '-' . $mode;
}
/**
*
* @return boolean
*/
public function validateParams() {
if ($this->data != null &&
$this->method != null ) {
return true;
} else {
return FALSE;
}
}
//it must be the same when you encrypt and decrypt
protected function getIV() {
return '1234567890123456';
//return mcrypt_create_iv(mcrypt_get_iv_size($this->cipher, $this->mode), MCRYPT_RAND);
return openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method));
}
/**
* @return type
* @throws Exception
*/
public function encrypt() {
if ($this->validateParams()) {
return trim(openssl_encrypt($this->data, $this->method, $this->key, $this->options,$this->getIV()));
} else {
throw new Exception('Invlid params!');
}
}
/**
*
* @return type
* @throws Exception
*/
public function decrypt() {
if ($this->validateParams()) {
$ret=openssl_decrypt($this->data, $this->method, $this->key, $this->options,$this->getIV());
return trim($ret);
} else {
throw new Exception('Invlid params!');
}
}
}
PHP AES encryption with mcrypt example, for older version 5.x
/**
Aes encryption
*/
class AES {
const M_CBC = 'cbc';
const M_CFB = 'cfb';
const M_ECB = 'ecb';
const M_NOFB = 'nofb';
const M_OFB = 'ofb';
const M_STREAM = 'stream';
protected $key;
protected $cipher;
protected $data;
protected $mode;
protected $IV;
/**
*
* @param type $data
* @param type $key
* @param type $blockSize
* @param type $mode
*/
function __construct($data = null, $key = null, $blockSize = null, $mode = null) {
$this->setData($data);
$this->setKey($key);
$this->setBlockSize($blockSize);
$this->setMode($mode);
$this->setIV("");
}
/**
*
* @param type $data
*/
public function setData($data) {
$this->data = $data;
}
/**
*
* @param type $key
*/
public function setKey($key) {
$this->key = $key;
}
/**
*
* @param type $blockSize
*/
public function setBlockSize($blockSize) {
switch ($blockSize) {
case 128:
$this->cipher = MCRYPT_RIJNDAEL_128;
break;
case 192:
$this->cipher = MCRYPT_RIJNDAEL_192;
break;
case 256:
$this->cipher = MCRYPT_RIJNDAEL_256;
break;
}
}
/**
*
* @param type $mode
*/
public function setMode($mode) {
switch ($mode) {
case AES::M_CBC:
$this->mode = MCRYPT_MODE_CBC;
break;
case AES::M_CFB:
$this->mode = MCRYPT_MODE_CFB;
break;
case AES::M_ECB:
$this->mode = MCRYPT_MODE_ECB;
break;
case AES::M_NOFB:
$this->mode = MCRYPT_MODE_NOFB;
break;
case AES::M_OFB:
$this->mode = MCRYPT_MODE_OFB;
break;
case AES::M_STREAM:
$this->mode = MCRYPT_MODE_STREAM;
break;
default:
$this->mode = MCRYPT_MODE_ECB;
break;
}
}
/**
*
* @return boolean
*/
public function validateParams() {
if ($this->data != null &&
$this->key != null &&
$this->cipher != null) {
return true;
} else {
return FALSE;
}
}
public function setIV($IV) {
$this->IV = $IV;
}
protected function getIV() {
if ($this->IV == "") {
$this->IV = mcrypt_create_iv(mcrypt_get_iv_size($this->cipher, $this->mode), MCRYPT_RAND);
}
return $this->IV;
}
/**
* @return type
* @throws Exception
*/
public function encrypt() {
if ($this->validateParams()) {
return trim(base64_encode(
mcrypt_encrypt(
$this->cipher, $this->key, $this->data, $this->mode, $this->getIV())));
} else {
throw new Exception('Invlid params!');
}
}
/**
*
* @return type
* @throws Exception
*/
public function decrypt() {
if ($this->validateParams()) {
return trim(mcrypt_decrypt(
$this->cipher, $this->key, base64_decode($this->data), $this->mode, $this->getIV()));
} else {
throw new Exception('Invlid params!');
}
}
}
Example for using AES class
include 'AES.php's; $inputText = "My text to encrypt"; $inputKey = "My text to encrypt"; $blockSize = 256; $aes = new AES($inputText, $inputKey, $blockSize); $enc = $aes->encrypt(); $aes->setData($enc); $dec=$aes->decrypt(); echo "After encryption: ".$enc."<br/>"; echo "After decryption: ".$dec."<br/>";Download PHP AES encryption example
Java AES encryption example
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
Aes encryption
*/
public class AES
{
private static SecretKeySpec secretKey ;
private static byte[] key ;
private static String decryptedString;
private static String encryptedString;
public static void setKey(String myKey){
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
System.out.println(key.length);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
System.out.println(key.length);
System.out.println(new String(key,"UTF-8"));
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getDecryptedString() {
return decryptedString;
}
public static void setDecryptedString(String decryptedString) {
AES.decryptedString = decryptedString;
}
public static String getEncryptedString() {
return encryptedString;
}
public static void setEncryptedString(String encryptedString) {
AES.encryptedString = encryptedString;
}
public static String encrypt(String strToEncrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
setEncryptedString(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
}
catch (Exception e)
{
System.out.println("Error while encrypting: "+e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
setDecryptedString(new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));
}
catch (Exception e)
{
System.out.println("Error while decrypting: "+e.toString());
}
return null;
}
public static void main(String args[])
{
final String strToEncrypt = "My text to encrypt";
final String strPssword = "encryptor key";
AES.setKey(strPssword);
AES.encrypt(strToEncrypt.trim());
System.out.println("String to Encrypt: " + strToEncrypt);
System.out.println("Encrypted: " + AES.getEncryptedString());
final String strToDecrypt = AES.getEncryptedString();
AES.decrypt(strToDecrypt.trim());
System.out.println("String To Decrypt : " + strToDecrypt);
System.out.println("Decrypted : " + AES.getDecryptedString());
}
}
Download Java AES encryption example
Python AES encryption example
Fully compatible with this tool: AES-CBC, PKCS#7 padding, key = the raw UTF-8 password bytes zero-padded (or truncated) to the key size, fixed IV 12345678b0z2345n, Base64 output. Requires the cryptography package (pip install cryptography).
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
IV = b"12345678b0z2345n" # fixed 16-byte IV used by aesencryption.net
def _key(password: str, bits: int) -> bytes:
n = bits // 8 # 16, 24 or 32 bytes
kb = password.encode("utf-8")
return (kb[:n]).ljust(n, b"\x00") # truncate if long, zero-pad if short
def _pad(data: bytes) -> bytes:
p = 16 - (len(data) % 16)
return data + bytes([p]) * p
def _unpad(data: bytes) -> bytes:
p = data[-1]
return data[:-p]
def encrypt(text: str, password: str, bits: int = 256) -> str:
c = Cipher(algorithms.AES(_key(password, bits)), modes.CBC(IV)).encryptor()
ct = c.update(_pad(text.encode("utf-8"))) + c.finalize()
return base64.b64encode(ct).decode("ascii")
def decrypt(b64: str, password: str, bits: int = 256) -> str:
d = Cipher(algorithms.AES(_key(password, bits)), modes.CBC(IV)).decryptor()
pt = d.update(base64.b64decode(b64)) + d.finalize()
return _unpad(pt).decode("utf-8").strip()
if __name__ == "__main__":
enc = encrypt("My text to encrypt.", "encryptor key", 256)
print("Encrypted:", enc)
print("Decrypted:", decrypt(enc, "encryptor key", 256))
Download Python AES encryption example
Go AES encryption example
Standard library only (crypto/aes, crypto/cipher, encoding/base64) — no external dependencies. Same parameters as above.
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
"strings"
)
// Fixed 16-byte IV used by aesencryption.net.
var iv = []byte("12345678b0z2345n")
// key = raw UTF-8 bytes of the password, zero-padded or truncated to bits/8.
func makeKey(password string, bits int) []byte {
key := make([]byte, bits/8) // zero-filled
copy(key, []byte(password)) // truncates if longer, leaves zeros if shorter
return key
}
func pkcs7Pad(data []byte) []byte {
p := aes.BlockSize - len(data)%aes.BlockSize
return append(data, bytes.Repeat([]byte{byte(p)}, p)...)
}
func pkcs7Unpad(data []byte) []byte {
return data[:len(data)-int(data[len(data)-1])]
}
func Encrypt(text, password string, bits int) (string, error) {
block, err := aes.NewCipher(makeKey(password, bits))
if err != nil {
return "", err
}
data := pkcs7Pad([]byte(text))
out := make([]byte, len(data))
cipher.NewCBCEncrypter(block, iv).CryptBlocks(out, data)
return base64.StdEncoding.EncodeToString(out), nil
}
func Decrypt(b64, password string, bits int) (string, error) {
block, err := aes.NewCipher(makeKey(password, bits))
if err != nil {
return "", err
}
ct, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return "", err
}
out := make([]byte, len(ct))
cipher.NewCBCDecrypter(block, iv).CryptBlocks(out, ct)
return strings.TrimSpace(string(pkcs7Unpad(out))), nil
}
func main() {
enc, _ := Encrypt("My text to encrypt.", "encryptor key", 256)
fmt.Println("Encrypted:", enc) // a8FC/4chLgfmBP1MAM0C/D8KqddSjxepiw6PLI6wlVk=
dec, _ := Decrypt(enc, "encryptor key", 256)
fmt.Println("Decrypted:", dec) // My text to encrypt.
}
Download Go AES encryption example
Rust AES encryption example
Uses the RustCrypto crates. Add to Cargo.toml: aes = "0.8", cbc = { version = "0.1", features = ["alloc"] }, base64 = "0.22". Shown for AES-256; for 128/192-bit keys use aes::Aes128/aes::Aes192 with a 16/24-byte key.
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use base64::{engine::general_purpose::STANDARD, Engine};
type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;
type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
// Fixed 16-byte IV used by aesencryption.net.
const IV: [u8; 16] = *b"12345678b0z2345n";
// key = raw UTF-8 bytes of the password, zero-padded or truncated to 32 bytes (AES-256).
fn make_key(password: &str) -> [u8; 32] {
let mut key = [0u8; 32];
let pw = password.as_bytes();
let n = pw.len().min(32);
key[..n].copy_from_slice(&pw[..n]);
key
}
fn encrypt(text: &str, password: &str) -> String {
let ct = Aes256CbcEnc::new(&make_key(password).into(), &IV.into())
.encrypt_padded_vec_mut::<Pkcs7>(text.as_bytes());
STANDARD.encode(ct)
}
fn decrypt(b64: &str, password: &str) -> String {
let data = STANDARD.decode(b64).expect("invalid base64");
let pt = Aes256CbcDec::new(&make_key(password).into(), &IV.into())
.decrypt_padded_vec_mut::<Pkcs7>(&data)
.expect("invalid padding (wrong key?)");
String::from_utf8(pt).unwrap().trim().to_string()
}
fn main() {
let enc = encrypt("My text to encrypt.", "encryptor key");
println!("Encrypted: {}", enc); // a8FC/4chLgfmBP1MAM0C/D8KqddSjxepiw6PLI6wlVk=
println!("Decrypted: {}", decrypt(&enc, "encryptor key"));
}
Download Rust AES encryption example
Kotlin AES encryption example
Runs on the JVM using javax.crypto — no external dependencies (PKCS5Padding is PKCS#7 for AES). Same parameters as the other examples: AES-CBC, key = raw UTF-8 password bytes zero-padded/truncated to the key size, fixed IV 12345678b0z2345n, Base64 output.
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
// Fixed 16-byte IV used by aesencryption.net.
val IV = "12345678b0z2345n".toByteArray(Charsets.UTF_8)
// key = raw UTF-8 bytes of the password, zero-padded or truncated to bits/8.
fun makeKey(password: String, bits: Int): ByteArray {
val key = ByteArray(bits / 8) // zero-filled
val pw = password.toByteArray(Charsets.UTF_8)
System.arraycopy(pw, 0, key, 0, minOf(pw.size, key.size))
return key
}
fun encrypt(text: String, password: String, bits: Int = 256): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(makeKey(password, bits), "AES"), IvParameterSpec(IV))
return Base64.getEncoder().encodeToString(cipher.doFinal(text.toByteArray(Charsets.UTF_8)))
}
fun decrypt(b64: String, password: String, bits: Int = 256): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(makeKey(password, bits), "AES"), IvParameterSpec(IV))
return String(cipher.doFinal(Base64.getDecoder().decode(b64)), Charsets.UTF_8).trim()
}
fun main() {
val enc = encrypt("My text to encrypt.", "encryptor key", 256)
println("Encrypted: $enc") // a8FC/4chLgfmBP1MAM0C/D8KqddSjxepiw6PLI6wlVk=
println("Decrypted: ${decrypt(enc, "encryptor key", 256)}")
}
Download Kotlin AES encryption example
JavaScript (Node.js) AES encryption example
Node.js using the built-in crypto module — no dependencies. (In the browser, this page already encrypts client-side — see the tool at the top.) Same parameters as above.
const crypto = require("crypto");
// Fixed 16-byte IV used by aesencryption.net.
const IV = Buffer.from("12345678b0z2345n", "utf8");
// key = raw UTF-8 bytes of the password, zero-padded or truncated to bits/8.
function makeKey(password, bits) {
const key = Buffer.alloc(bits / 8); // zero-filled
Buffer.from(password, "utf8").copy(key); // truncates if longer, leaves zeros if shorter
return key;
}
function encrypt(text, password, bits = 256) {
const c = crypto.createCipheriv("aes-" + bits + "-cbc", makeKey(password, bits), IV);
return Buffer.concat([c.update(text, "utf8"), c.final()]).toString("base64");
}
function decrypt(b64, password, bits = 256) {
const d = crypto.createDecipheriv("aes-" + bits + "-cbc", makeKey(password, bits), IV);
return Buffer.concat([d.update(b64, "base64"), d.final()]).toString("utf8").trim();
}
const enc = encrypt("My text to encrypt.", "encryptor key", 256);
console.log("Encrypted:", enc); // a8FC/4chLgfmBP1MAM0C/D8KqddSjxepiw6PLI6wlVk=
console.log("Decrypted:", decrypt(enc, "encryptor key", 256));
Download JavaScript AES encryption example
More free online tools
Found this tool useful? A small donation helps keep it free and ad-light.