简体   繁体   中英

JPA: Using AttributeConverter automatically decrypt in JPA query

I wrote my own AttributeConverter to encrypt and decrypt Strings and its similar to:

@Converter
public class CryptoConverter implements AttributeConverter<String, String> {

@Override
public String convertToDatabaseColumn(String attribute)  {
 //works fine
}

@Override
public String convertToEntityAttribute(String dbData) {
//works fine
}

}

My entity class is using this converter:

@Entity
@PublishKeyword
@Table(name = "CARD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Card {

//...

@Column(name = "CARD_LAST_4_DIGITS")
@Convert(converter = CryptoConverter.class)
@Attribute(keyword = "CARD_CARDLAST4DIGITS", resolvedKeyword = "cardLast4Digits", length = 100)
private String cardLast4Digits;

//...
}

Everything works fine until here. The data I had set is encrypted in the database and is also decrypted after getting the result set. But the CryptoConverter is not used in automatically in JPA query. ?

@Override
public Card findCard(String lastFour, String tenantId, EntityManager entityManager) {
    Query query = entityManager.createQuery("SELECT e FROM Card e where e.cardLast4Digits = :lastFour").setParameter("lastFour", "lastFour");
    List<Card> cardList = query.getResultList();
    if (cardList != null && cardList.size() > 0) {
        return cardList.get(0);
    }
    return null;
}

The input is also being converted. So if you use asymmetric encryption (so every time you encrypt the same value you get different output) then filtering will never work.

Solution can be to use symmetric encryption or add a column that uses a hash (which is always the same for the same value) and filter on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM