001package io.ebean.config.dbplatform.h2;
002
003import io.ebean.config.dbplatform.AbstractDbEncrypt;
004import io.ebean.config.dbplatform.DbEncryptFunction;
005
006/**
007 * H2 encryption support via encrypt decrypt function.
008 */
009public class H2DbEncrypt extends AbstractDbEncrypt {
010
011  public H2DbEncrypt() {
012    this.varcharEncryptFunction = new H2VarcharFunction();
013    this.dateEncryptFunction = new H2DateFunction();
014  }
015
016  /**
017   * For H2 encrypt function returns false binding the key before the data.
018   */
019  @Override
020  public boolean isBindEncryptDataFirst() {
021    return false;
022  }
023
024  private static class H2VarcharFunction implements DbEncryptFunction {
025
026    @Override
027    public String getDecryptSql(String columnWithTableAlias) {
028      // Hmmm, this looks ugly - checking with H2 Database folks.
029      return "TRIM(CHAR(0) FROM UTF8TOSTRING(DECRYPT('AES', STRINGTOUTF8(?), " + columnWithTableAlias + ")))";
030    }
031
032    @Override
033    public String getEncryptBindSql() {
034      return "ENCRYPT('AES', STRINGTOUTF8(?), STRINGTOUTF8(?))";
035    }
036
037  }
038
039  private static class H2DateFunction implements DbEncryptFunction {
040
041    @Override
042    public String getDecryptSql(String columnWithTableAlias) {
043      return "PARSEDATETIME(TRIM(CHAR(0) FROM UTF8TOSTRING(DECRYPT('AES', STRINGTOUTF8(?), " + columnWithTableAlias + "))),'yyyyMMdd')";
044    }
045
046    @Override
047    public String getEncryptBindSql() {
048      return "ENCRYPT('AES', STRINGTOUTF8(?), STRINGTOUTF8(FORMATDATETIME(?,'yyyyMMdd')))";
049    }
050
051  }
052}