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;
}
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With