0

I found this code on a website. I can't understand how to decode this. Can you help me?

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class AES {
    
    public static String encrypt(String strToEncrypt) throws Exception {
        byte[] plaintext = strToEncrypt.getBytes("UTF-8");
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        SecretKey key = keygen.generateKey();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] ciphertext = cipher.doFinal(plaintext);
        return Base64.getEncoder().encodeToString(ciphertext);
    }

}
1
  • 4
    Unfortunately you found a poor example. As it stands you cannot decrypt the cipher-text - that's pretty problematic. For a symmetric cipher like AES you need some way to specify (or derive) the key; so at least a key or key-phrase is missing as parameter. Also, in CBC mode you really should use an IV. Best advice: find a better example - stackoverflow has several much better than this Commented Aug 11, 2020 at 11:17

1 Answer 1

3

Welcome to Stackoverflow. Below you find a full working example of an AES CBC String en-/decryption. Please note that you need to store the randmly created key & initialization vectore securely to (later) encrypted data because otherwise there is (realy) NO way to recover your data. The same key and iv needs to be used for encryption and decryption.

As the key & iv are byte arrays I encoded them to Base64 for a better storage.

Security warning: This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling. The code is for educational purposes only and should not be used in production!

result:

AES CBC String Encryption with random key + iv
This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.
The code is for educational purposes only and should not be used in production.

save the key and iv securely, without the data it will be NOT possible to decrypt !!
key in Base64-format: Nf41yG0F+MdFQnp3p3mIrWOk+2kxQ/LmyVcHKEKi5sQ=
iv in Base64-format:  yICmqsMaIdwsYsUDUsLWnA==
plaintext:     The quick brown fox jumps over the lazy dog
ciphertext:    PJNEV3H3Zh3TQx7B9jpg29gV59LgJ6baOpNM82dMOpPClJouYnq+hKVUQTDEkkdI
decryptedtext: The quick brown fox jumps over the lazy dog

code:

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AesCbcTextEncryptionRandomKeyIv {
    public static void main(String[] args) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        System.out.println("AES CBC String Encryption with random key + iv");
        System.out.println("This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.");
        System.out.println("The code is for educational purposes only and should not be used in production.\n");

        String plaintext = "The quick brown fox jumps over the lazy dog";

        // generate a random key & initialization vector
        byte[] key = new byte[32]; // key for aes 256 encryption, 32 byte length
        byte[] iv = new byte[16]; // initialization vector with 16 byte length
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(key);
        secureRandom.nextBytes(iv);
        System.out.println("save the key and iv securely, without the data it will be NOT possible to decrypt !!");
        // convert key & iv in base64 format for storage reasons
        String keyBase64 = Base64.getEncoder().encodeToString(key);
        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        System.out.println("key in Base64-format: " + keyBase64);
        System.out.println("iv in Base64-format:  " + ivBase64);

        // encryption
        String ciphertext = encrypt(keyBase64, ivBase64, plaintext);
        System.out.println("plaintext:     " + plaintext);
        System.out.println("ciphertext:    " + ciphertext);

        // decryption
        String decryptedtext = decrypt(keyBase64, ivBase64, ciphertext);
        System.out.println("decryptedtext: " + decryptedtext);

    }
    public static String encrypt(String keyBase64, String ivBase64, String plaintext)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(ivBase64));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)));
    }

    public static String decrypt(String keyBase64, String ivBase64, String ciphertext)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(ivBase64));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.