github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/cry/gocrypt.go (about)

     1  package cry
     2  
     3  // GocryptInterface is facing the format gocrypt option library
     4  type GocryptInterface interface {
     5  	Encrypt(interface{}) error
     6  	Decrypt(interface{}) error
     7  }
     8  
     9  // GocryptOption is facing the format encryption and decryption format
    10  type GocryptOption interface {
    11  	Encrypt(plainText []byte) (string, error)
    12  	Decrypt(chipherText []byte) (string, error)
    13  }
    14  
    15  // Option contains an option from initial algorithm encryptioin & decryption.
    16  type Option struct {
    17  	AESOpt  GocryptOption
    18  	DESOpt  GocryptOption
    19  	RC4Opt  GocryptOption
    20  	Custom  map[string]GocryptOption
    21  	Prefix  string
    22  	Postfix string
    23  }
    24  
    25  // New create and initialize new option for struct field encryption.
    26  //
    27  // It needs option from aes, rc4, or des for initialitaion
    28  func New(opt *Option) *Option {
    29  	return opt
    30  }
    31  
    32  // Encrypt is function to set struct field encrypted
    33  func (opt *Option) Encrypt(structVal interface{}) error {
    34  	return read(structVal, opt.encrypt)
    35  }
    36  
    37  // Decrypt is function to set struct field decrypted
    38  func (opt *Option) Decrypt(structVal interface{}) error {
    39  	return read(structVal, opt.decrypt)
    40  }
    41  
    42  func (opt *Option) encrypt(algo string, plainText string) (string, error) {
    43  	plainByte := []byte(plainText)
    44  	switch algo {
    45  	case "aes":
    46  		return opt.AESOpt.Encrypt(plainByte)
    47  	case "des":
    48  		return opt.DESOpt.Encrypt(plainByte)
    49  	case "rc4":
    50  		return opt.RC4Opt.Encrypt(plainByte)
    51  	default:
    52  		return opt.AESOpt.Encrypt(plainByte)
    53  	}
    54  }
    55  
    56  func (opt *Option) decrypt(algo string, chipperText string) (string, error) {
    57  	chipperByte := []byte(chipperText)
    58  	switch algo {
    59  	case "aes":
    60  		return opt.AESOpt.Decrypt(chipperByte)
    61  	case "des":
    62  		return opt.DESOpt.Decrypt(chipperByte)
    63  	case "rc4":
    64  		return opt.RC4Opt.Decrypt(chipperByte)
    65  	default:
    66  		return opt.AESOpt.Decrypt(chipperByte)
    67  	}
    68  }