Skip to content

Latest commit

 

History

History
139 lines (94 loc) · 3.52 KB

File metadata and controls

139 lines (94 loc) · 3.52 KB

Greenbone Logo

dbcrypt Package Documentation

This package provides functions for encrypting and decrypting fields of entities persisted with GORM using the AES algorithm. It uses the GCM mode of operation for encryption, which provides authentication and integrity protection for the encrypted data. It can be used to encrypt / decrypt sensitive data using gorm hooks (see example)

Example Usage

Here is an example of how to use the dbcrypt package:

package main

import (
	"fmt"

	"github.com/example/dbcrypt"
)

type Person struct {
	gorm.Model
	Field1   string
	PwdField string `encrypt:"true"`
}

func (a *MyTable) encrypt(tx *gorm.DB) (err error) {
	err = cryptor.EncryptStruct(a)
	if err != nil {
        	err := tx.AddError(fmt.Errorf("unable to encrypt password %w", err))
		if err != nil {
			return err
		}
		return err
	}
	return nil
}

func (a *MyTable) BeforeCreate(tx *gorm.DB) (err error) {
	return a.encrypt(tx)
}

func (a *MyTable) AfterFind(tx *gorm.DB) (err error) {
	err = cryptor.DecryptStruct(a)
	if err != nil {
		err := tx.AddError(fmt.Errorf("Unable to decrypt password %w", err))
		if err != nil {
			return err
		}
		return err
	}
	return nil
}

In this example, a Person struct is created and encrypted using the DBCrypt struct. The encrypted struct is then saved to the database. Finally the struct is decrypted when the gorm hook is activated.


dbcrypt

import "github.com/greenbone/opensight-golang-libraries/pkg/dbcrypt"

Index

func Decrypt

func Decrypt(encrypted string, key []byte) (string, error)

func Encrypt

func Encrypt(plaintext string, key []byte) (string, error)

type DBCrypt

type DBCrypt[T any] struct {
    // contains filtered or unexported fields
}

func (*DBCrypt[T]) DecryptStruct

func (d *DBCrypt[T]) DecryptStruct(data *T) error

DecryptStruct decrypts all fields of a struct that are tagged with `encrypt:"true"`

func (*DBCrypt[T]) EncryptStruct

func (d *DBCrypt[T]) EncryptStruct(data *T) error

EncryptStruct encrypts all fields of a struct that are tagged with `encrypt:"true"`

Generated by gomarkdoc

License

Copyright (C) 2022-2023 [Greenbone AG][Greenbone AG]

Licensed under the GNU General Public License v3.0 or later.