Encrypt string using AES 128 – Java

You need Apache Commons Codec.

package encryption.aes;
 
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
 
public class aes128 {  
 
    public static void main(String args[]) 
    {
        String plain = "testtesttesttesttesttesttesttest";
        String ivkey = "abcdefgh12345678";
 
        byte[] ivraw = ivkey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(ivraw, "AES");
 
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(plain.getBytes());
            System.out.println(new String(Base64.encodeBase64(encrypted)));
 
        } catch (NoSuchAlgorithmException 
                | NoSuchPaddingException 
                | InvalidKeyException 
                | IllegalBlockSizeException 
                | BadPaddingException e) {
        }
    }
}

Output:
yS2u7FGpXyumAWryjBCfOMktruxRqV8rpgFq8owQnzgvlyep0drjQXvZ0+XXcLxD

Categories: Java Tags: , , , , , , , ,
%d bloggers like this: