-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt_string.go
97 lines (87 loc) · 2.3 KB
/
encrypt_string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package simple_encrypt
import (
"database/sql/driver"
"errors"
)
// EncryptString is for encrypt a string. If anything error in the process of scanner or valuer,
// they will return the raw data, instead of nil
type EncryptString struct {
keyName string
raw *string
}
// Scan scans the value src from the database to the type EncryptString
func (s *EncryptString) Scan(src interface{}) error {
// src might be null
if src == nil {
s.raw = nil
return nil
}
// The src type must be string or []byte
var source string
switch src.(type) {
case string:
source = src.(string)
case []byte:
source = string(src.([]byte))
default:
s.raw = nil
return errors.New("incompatible type for scan")
}
// Have to recover from panic because we always want to get the original data no matter what happen
defer recoverFromPanicEncryptString(s, source)
// Decrypt the source by key with given key name
plainTextString, err := decrypt(source, keys[s.keyName])
if err != nil {
s.raw = &source
return nil
}
s.raw = &plainTextString
return nil
}
// Value encrypts the value and save in the database
func (s EncryptString) Value() (driver.Value, error) {
if s.raw == nil {
return nil, nil
}
cipherTextString, err := encrypt(*s.raw, keys[s.keyName])
if err != nil {
return *s.raw, err
}
return cipherTextString, nil
}
// Int gets the raw string
func (s *EncryptString) String() string {
if s.raw == nil {
return ""
}
return *s.raw
}
// SetKeyName sets the key
func (s *EncryptString) SetKeyName(keyName string) {
s.keyName = keyName
}
// SetRaw sets the raw
func (s *EncryptString) SetRaw(raw *string) {
s.raw = raw
}
// NewEncryptString news a default EncryptString
func NewEncryptString(raw *string) EncryptString {
return EncryptString{
keyName: DefaultKeyName,
raw: raw,
}
}
// NewEncryptStringWithKeyName news an EncryptString with given key name
// you must only use NewDefaultEncryptString or NewEncryptString to new an EncryptString
func NewEncryptStringWithKeyName(keyName string, raw *string) EncryptString {
return EncryptString{
keyName: keyName,
raw: raw,
}
}
// recoverFromPanicEncryptString recovers from panic and get the plain string for EncryptString
func recoverFromPanicEncryptString(i *EncryptString, source string) {
if r := recover(); r != nil {
i.raw = &source
}
}