Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java How to check value is already AES encrypted;

I have created a tool to encrypt my table data using AES encryption.

Encryption method

public String encrypt(String plainText) throws Exception {

        byte[] cipherBytes = null;

        log.info("Started encryption...");

        System.out.println("value before encryption :" + plainText);

        log.info("value before encryption :" + plainText);

        if (plainText != null && !plainText.isEmpty()) {
            if (cipher != null && key != null) {
                byte[] ivByte = new byte[cipher.getBlockSize()];
                IvParameterSpec ivParamsSpec = new IvParameterSpec(ivByte);
                cipher.init(Cipher.ENCRYPT_MODE, key, ivParamsSpec);
                cipherBytes = cipher.doFinal(plainText.getBytes());
                log.info("Completed encryption.");
                log.info("Encrypted data : " + new String(cipherBytes, "UTF8"));
                System.out.println("value after encryption" + Hex.encodeHexString(cipherBytes));
                log.info("value after encryption" + Hex.encodeHexString(cipherBytes));
                return Hex.encodeHexString(cipherBytes);
            } else {
                log.info("Encryption failed, cipher, key is null.");
                throw new RuntimeException(
                        "Encryption failed, cipher, key  is null.");
            }

        }


        return plainText;


    }
  • input String: John Doee
  • encrypted output: 4aa2173cb653f89e109b23218ecaea7f

I want to avoid double encrypting my table data. I want to check if existing record is already encrypted. Is there any way to check this?

like image 605
Niranga Sandaruwan Avatar asked Dec 05 '22 11:12

Niranga Sandaruwan


1 Answers

After encryption, prepend some prefix such as AES:. When decrypting, check for presence of the prefix (and remove it, obviously).

Plenty of cipher implementations do similar things, where the first few bytes identify the algorithm.

As with any good encryption scheme, only the key must be secret. The algorithm can be public without compromising security.


The only edge case is if true plaintext begins with the prefix. If you think this is worth considering then you can reduce the risk by choosing an unlikely prefix (perhaps taking advantage of knowledge of the plaintext). For further assurance you could look at the length of the input, as the length of true ciphertext is guaranteed to be a multiple of the block size.

like image 156
Michael Avatar answered Dec 23 '22 14:12

Michael