How to use pgcrypto with go-pg for column encryption?

364 views Asked by At

Could you help me please with my problem. I'm trying to use column encryption for postgres and there is one small question: how I can achieve transformation value of column (ex: "test_value") to PGP_SYM_ENCRYPT('test_value', 'KEY') in "insert" sql query? As I understood, the custom types can be the solution for me, but some things isn't clear... Maybe anyone has an example for my case?

(I see this aws docs about pgcrypto using: https://docs.aws.amazon.com/dms/latest/sql-server-to-aurora-postgresql-migration-playbook/chap-sql-server-aurora-pg.security.columnencryption.html)

What I did:


type sstring struct {
    string
}

var _ types.ValueAppender = (*sstring)(nil)

func (tm sstring) AppendValue(b []byte, flags int) ([]byte, error) {
    if flags == 1 {
        b = append(b, '\'')
    }
    b = []byte("PGP_SYM_ENCRYPT('123456', 'AES_KEY')")
    if flags == 1 {
        b = append(b, '\'')
    }
    return b, nil
}

var _ types.ValueScanner = (*sstring)(nil)

func (tm *sstring) ScanValue(rd types.Reader, n int) error {
    if n <= 0 {
        tm.string = ""
        return nil
    }

    tmp, err := rd.ReadFullTemp()
    if err != nil {
        return err
    }

    tm.string = string(tmp)

    return nil
}

type model struct {
    ID        uint      `pg:"id"`
    Name      string    `pg:"name"`
    Crypto    sstring   `pg:"crypto,type:sstring"`

    tableName struct{} `pg:"models"`
}
----------
_, err := r.h.ModelContext(ctx, model).Insert()

And... the process just do nothing. Do not respond, do not fall, do not create row in sql table.. Nothing.

Anyway. My question is how to implement wrap some column by sql function using pg-go orm.

I tried to use https://github.com/go-pg/pg/blob/v10/example_custom_test.go#L13-L49 as custom type handler example.. But smth went wrong. =(

0

There are 0 answers