0

Im trying to encrypt some user data in the DB then decrepit it back when showing it to users

Im doing this using JPA, Eclipse link 2.7.1, and MYSql 5.6

the User entity looks like that:

@Entity
@Cacheable(false)
@Table(name = "user_table")
public class User implements Serializable {

// some fields
    @Lob
    @Column(name = "about_me")
    @Convert(converter = EncryptorConverter.class)
    String aboutMe;

// setters and getters
}

and here under is the EncryptorConverter.class

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import java.util.*;

@Converter

public class EncryptorConverter implements javax.persistence.AttributeConverter<String, String> {

    String key = "************"; // 128 bit key
    String initVector = "**************"; // 16 bytes IV
    IvParameterSpec iv;
    SecretKeySpec skeySpec;
    static Cipher cipher;
    static Cipher deipher;

    private static final Logger LOG = Logger.getLogger(
            EncryptorConverter.class.getName());


    public EncryptorConverter() {
        try {
            iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            deipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            deipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

    }


    @Override
    public String convertToDatabaseColumn(String attribute) {

        if (attribute == null) {
            return "";
        }
        try {
            byte[] encrypted = cipher.doFinal(attribute.getBytes("UTF-8"));
            return java.util.Base64.getEncoder().encodeToString(encrypted);
        } catch (BadPaddingException e) {
            // do nothing
        } catch (javax.crypto.IllegalBlockSizeException e) {
            // do nothing
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

        return "";
    }

    @Override
    public String convertToEntityAttribute(String dbData) {

        if (dbData == null) {
            return "";
        }
        try {
            byte[] original = deipher.doFinal(java.util.Base64.getDecoder().decode(dbData.getBytes("UTF-8")));
            return new String(original, "UTF-8");
        } catch (javax.crypto.IllegalBlockSizeException e) {
            // do nothing
        } catch (BadPaddingException e) {
            // do nothing
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

        return "";
    }

}

My problem is sometimes when I read the decoded aboutMe field from the user entity it looks like having strange chars like this "��t����a:i3��5�o" and sometimes it'll look just fine without any strange chars.

Do I do anything wrong with the decoding steps?

I really appreciate your help.

7
  • First, you shouldn't ignore exceptions like you're doing. Second, you shouldn't use a single Cipher instance for all your operations. Create a Cipher every time each of the methods is called. Finally: if the input is null, you store an empty string in database, and when reading that empty string in database, you decipher it. Both methods should return null if the argument is null.
    – JB Nizet
    Aug 26, 2018 at 16:52
  • I know that I shouldn't ignore exceptions but Im only ignoring those 2 specific Exceptions (BadPaddingException & IllegalBlockSizeException ) cause if they happen it'll not do any harm effect and they just stop the process (I got a lot of recommendations to do so here in stackOverFlow). why should I create a new instance for every method call? I don't get this part. Aug 26, 2018 at 17:00
  • 1
    I repeat: don't, ever, ignore exceptions. Whoever told you to do that is wrong. And you ignore all exceptions: catch (Exception ex) . An exception signals a bug, and you don't want to store corrupted data silently in your database. You want an error to be thrown to leave your database in a good state, and to know that your code has a bug.
    – JB Nizet
    Aug 26, 2018 at 17:05
  • 1
    Regarding your question: I don't know if JPA creates a single instance of your converter or if it creates one for each conversion. If the former: you share a stateful, non-thread-safe Cipher between threads, which is wrong. If the latter, you create two Ciphers when you only need one, which is wasteful.
    – JB Nizet
    Aug 26, 2018 at 17:05
  • yeah im not ignoring the "Exception" Im logging it, and also I dont want throwing it to stop the operation, my main problem is not encrypting the data, my main problem is decepting it, as I've said sometimes the decryption is going through fine and sometimes it has strange chars Aug 26, 2018 at 17:09

0

Your Answer

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

Browse other questions tagged or ask your own question.