有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Hibernate@ColumnTransformer加密Postgres中的列

我正在尝试加密prostrgres数据库中的一列。列名为“bytea”类型的“test”

我的enity代码如下

@ColumnTransformer(
          forColumn="test", 
          read="pgp_sym_encrypt(test::bytea, 'mySecretKey')", 
          write="pgp_sym_decrypt(?, 'mySecretKey')")
private String test;

当我试图检索实体时,我得到了如下加密数据。如何以编程方式获取解密值?但如果我执行postgres select查询,就会得到实际值

  "test": "\\xc30d04070302474627ea0994ea657bd24401aaa5543862d57524a407e5dbe2ee0f6f0f33ea4f4474f5bc801dca5d32956d41a975505b12ac000f124177bdc2f4507cbfd724d716aaa513ba46f004dfefd3b2b32eb6"
  1. 当我试图持久化实体时,我得到了下面的错误

ERROR: column "test" is of type bytea but expression is of type character varying


共 (2) 个答案

  1. # 1 楼答案

    您需要使用pgp_sym_encrypt进行写入,使用pgp_sym_decrypt进行读取。你做了相反的事

    @ColumnTransformer(
        read =  "pgp_sym_decrypt(" +
                "    test, " +
                "    current_setting('encrypt.key')" +
                ")",
        write = "pgp_sym_encrypt( " +
                "    ?, " +
                "    current_setting('encrypt.key')" +
                ") "
    )
    @Column(columnDefinition = "bytea")
    private String test;
    

    因为在映射中硬编码加密密钥听起来不是一个好主意,我们将使用PostgreSQL支持用户定义的设置

    因此,^{}存储在postgresql.conf配置文件中:

    encrypt.key = 'Wow! So much security.'
    

    这个example is on GitHub像个符咒

  2. # 2 楼答案

    虽然这很有魅力,但不能将其视为产品通用解决方案,而且这并不方便,因为在多个数据库上工作将是一场噩梦。可能还有其他选择,比如拱顶或使用jasypt将是一个良好的开端