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 *
009 * @author rbygrave
010 */
011public class H2DbEncrypt extends AbstractDbEncrypt {
012
013  public H2DbEncrypt() {
014    this.varcharEncryptFunction = new H2VarcharFunction();
015    this.dateEncryptFunction = new H2DateFunction();
016  }
017
018  /**
019   * For H2 encrypt function returns false binding the key before the data.
020   */
021  @Override
022  public boolean isBindEncryptDataFirst() {
023    return false;
024  }
025
026  private static class H2VarcharFunction implements DbEncryptFunction {
027
028    @Override
029    public String getDecryptSql(String columnWithTableAlias) {
030      // Hmmm, this looks ugly - checking with H2 Database folks.
031      return "TRIM(CHAR(0) FROM UTF8TOSTRING(DECRYPT('AES', STRINGTOUTF8(?), " + columnWithTableAlias + ")))";
032    }
033
034    @Override
035    public String getEncryptBindSql() {
036      return "ENCRYPT('AES', STRINGTOUTF8(?), STRINGTOUTF8(?))";
037    }
038
039  }
040
041  private static class H2DateFunction implements DbEncryptFunction {
042
043    @Override
044    public String getDecryptSql(String columnWithTableAlias) {
045      return "PARSEDATETIME(TRIM(CHAR(0) FROM UTF8TOSTRING(DECRYPT('AES', STRINGTOUTF8(?), " + columnWithTableAlias + "))),'yyyyMMdd')";
046    }
047
048    @Override
049    public String getEncryptBindSql() {
050      return "ENCRYPT('AES', STRINGTOUTF8(?), STRINGTOUTF8(FORMATDATETIME(?,'yyyyMMdd')))";
051    }
052
053  }
054}