How to generate AES keys for encryption and decryption using AES/CBC/PKCS5Padding


fern:

I am trying to create AES key using this code

    public static SecretKey generateSecretKey() {

        KeyGenerator generator;
        try {

            generator = KeyGenerator.getInstance(StaticHandler.AES_KEY_MODE); // Is "AES"
            generator.init(StaticHandler.AES_KEY_SIZE); // The AES key size in number of bits // Is "128"

            return generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

But use this code to encrypt/decrypt


    public static String encrypt(String data, SecretKey secret, Charset charset) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secret);

            return new String(cipher.doFinal(data.getBytes()), charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String decrypt(String data, @NonNull SecretKey secret, Charset charset) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secret);

            return new String(cipher.doFinal(data.getBytes()), charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

get errorjava.security.InvalidKeyException: Parameters missing

I'm guessing I need to add some salt, although I don't know how to do it with the generated key. I'd like to avoid generating passwords, but I wouldn't mind if it was securely generated.

EDIT: In hindsight, if I'm sending packets over the network, should I use GCM or CBC encryption? Keep in mind that I'm using randomly generated keys and I don't keep them for sessions (randomly generated per client and server session).

dave_thompson_085:

No, you don't need salt, your keys are actually fine. CBC mode requires an IV (Initialization Vector), see Wikipedia , and the IV should be different for each encrypted data, but each decryption must use the same value as the corresponding encryption. (Added) For CBC, though not otherwise, it is also critical for the IV that the adversary cannot predict the IV; the easiest and most common way to achieve uniqueness and unpredictability is to use a secure random number (aka bit) generator, such as Java's SecureRandom. If you want to know the other way, it's not really a programming question, it's more applicable to crypto.SX or security.SX where multiple Q's already exist.

You can explicitly generate the IV and assign it to encrypt and decrypt, or allow the encryption operation to generate the IV itself, get the IV from the encrypted cipher, and assign it to the decrypted cipher. In either case, the encryptor must provide the value that the decryptor will use; the common approach is to simply concatenate the IV with the ciphertext (making them easy to match correctly), but there are also other discussion methods. See https://docs.oracle.com/en-us/java/javase/11/security/java-cryptography-architecture-jca-reference-guide.html in the "Initializing the Cryptographic Object" section (following the two paragraphs) box within the method declaration box) and "Managing Algorithm Parameters".


Also don't store in ciphertextString . Java Stringis designed to handle valid characters, not arbitrary bytes. "Decoding" the ciphertext into a string and "encoding" it into binary will pretty much lose or change some data, especially if you allow for different character sets on both ends, and with modern cryptography, the ciphertext will not be changed at all Destroy all or most of your data. Since the ciphertext is bytes, it is better to treat it as byte[]; . If something like a URL is n't possible because you want to put it , use one of several schemes designed to encode arbitrary bytes as text so they can be recovered correctly: base64 (3 or 4 major variants, plus many minor variants), base32, hex/base16, URL "percent" encoding, MIME reference printable, yencode, Kermit, PPP, etc. j8+ provides a newer base64 variant (ie not uuencode).java.util.Base64

Conversely, while "plain text" in modern encryption can actually be any form of data, if you do have text and you belong, Stringyou should encode it with the appropriate charset before encryption, and decrypt it with the same character set to decode, i.e.

 byte[] ctext = encCipher.doFinal (input.getBytes(charset));
 ...
 String output = new String (decCipher.doFinal (ctext), charset);

While the "best" character set may vary by data, if you don't know what the data is or don't want to bother analyzing it, it 's pretty good UTF-8for most textual data , and is very popular and standard.

Related


Android encryption/decryption using AES

h4rd4r7c0r3: Is there a good example of how to encrypt and decrypt images and other files using AES on Android ? Nacho L.: Warning: this answer contains code you shouldn't use because it's not secure (use SHA1PRNG for key derivation, and use AES in ECB mode) I

File encryption and decryption using AES

Rekha Ahir public long copyStreamsLong(InputStream in, OutputStream out, long sizeLimit) throws IOException { long byteCount = 0; IOException error = null; long totalBytesRead = 0; try { String key = "C4F9EA21977047

Android encryption/decryption using AES

h4rd4r7c0r3: Is there a good example of how to encrypt and decrypt images and other files using AES on Android ? Nacho L.: Warning: this answer contains code that you shouldn't use because it's not secure (use SHA1PRNG for key derivation, and use AES in ECB mo

File encryption and decryption using AES

Rekha Ahir public long copyStreamsLong(InputStream in, OutputStream out, long sizeLimit) throws IOException { long byteCount = 0; IOException error = null; long totalBytesRead = 0; try { String key = "C4F9EA21977047

AES encryption and decryption using Java

Yogesh D Here's what I'm doing, it might seem a little clunky, but it might help you out. I get one BadPaddingException. Read almost all related topics but couldn't find a proper solution. I am new to encryption decryption programming and need to implement it

AES encryption and decryption using Java

Yogesh D Here's what I'm doing, it might seem a little clunky, but it might help you out. I get one BadPaddingException. Read almost all related topics but couldn't find a proper solution. I am new to encryption decryption programming and need to implement it

Android encryption/decryption using AES

h4rd4r7c0r3: Is there a good example of how to encrypt and decrypt images and other files using AES on Android ? Nacho L.: Warning: this answer contains code you shouldn't use because it's not secure (use SHA1PRNG for key derivation, and use AES in ECB mode) I

File encryption and decryption using AES

Rekha Ahir public long copyStreamsLong(InputStream in, OutputStream out, long sizeLimit) throws IOException { long byteCount = 0; IOException error = null; long totalBytesRead = 0; try { String key = "C4F9EA21977047

AES encryption using Java and decryption using Java

rkj : I'm making an application that requires Java-based AES encryption and JavaScript-based decryption. I am using the following code as base form for encryption. public class AESencrp { private static final String ALGO = "AES"; private static final byte

AES encryption using Java and decryption using Java

j I'm making an application that requires Java-based AES encryption and JavaScript-based decryption. I am using the following code as base form for encryption. public class AESencrp { private static final String ALGO = "AES"; private static final byte[] k

AES encryption using Java and decryption using Java

rkj : I'm making an application that requires Java-based AES encryption and JavaScript-based decryption. I am using the following code as base form for encryption. public class AESencrp { private static final String ALGO = "AES"; private static final byte

File Encryption/Decryption with AES using Linux

Ahmed 202: I am using openwrt linux distribution and want to encrypt files using AES. How can I do this quickly and easily, and how can I or someone else decrypt it again? Vasily G: The fastest and easiest way is to use opensslutil (provided by the package ope

File Encryption/Decryption with AES using Linux

Ahmed 202: I am using openwrt linux distribution and want to encrypt files using AES. How can I do this quickly and easily, and how can I or someone else decrypt it again? Vasily G: The fastest and easiest way is to use opensslutil (provided by the package ope

AES encryption/decryption in javascript using CryptoJS

Anthracene I am trying to send AES encrypted messages between javascript and php using a shared key. In Javascript, I am using the CryptoJS library. In php, I am using mycrypt. I am trying to construct an encrypted message in javascript and then decrypt it in

AES encryption/decryption in javascript using CryptoJS

Anthracene I am trying to send AES encrypted messages between javascript and php using a shared secret. In Javascript, I am using the CryptoJS library. In php, I am using mycrypt. I am trying to construct an encrypted message in javascript and then decrypt it

AES encryption/decryption in javascript using CryptoJS

Anthracene I am trying to send AES encrypted messages between javascript and php using a shared secret. In Javascript, I am using the CryptoJS library. In php, I am using mycrypt. I am trying to construct an encrypted message in javascript and then decrypt it

File Encryption/Decryption with AES using Linux

Ahmed 202: I am using openwrt linux distribution and want to encrypt files using AES. How can I do this quickly and easily, and how can I or someone else decrypt it again? Vasily G: The fastest and easiest way is to use opensslutil (provided by the package ope

AES encryption/decryption in javascript using CryptoJS

Anthracene I am trying to send AES encrypted messages between javascript and php using a shared secret. In Javascript, I am using the CryptoJS library. In php, I am using mycrypt. I am trying to construct an encrypted message in javascript and then decrypt it