Skip to content

Commit

Permalink
optimize: safe.String and Encryption logic
Browse files Browse the repository at this point in the history
Signed-off-by: 孙林耀 <sunlinyao@vip.qq.com>
  • Loading branch information
MicroOps-cn committed May 8, 2024
1 parent 2da8f4f commit f2918fa
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
7 changes: 7 additions & 0 deletions safe/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,13 @@ func Encrypt(originalBytes []byte, key string, o *EncryptOptions) (string, error
const ciphertextPrefix = "{CRYPT}"

func Decrypt(cipherString, key string) ([]byte, error) {
switch len(key) {
case 8, 16, 24, 32:
default:
hash := sha256.New()
hash.Write([]byte(key))
key = string(hash.Sum(nil))
}
if len(cipherString) <= len(ciphertextPrefix)+5 {
return nil, errors.New("invalid ciphertext")
}
Expand Down
7 changes: 5 additions & 2 deletions safe/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ func (e String) UnsafeString() (string, error) {
return "", nil
}
if strings.HasPrefix(e.value, ciphertextPrefix) {
fmt.Println(e.getSecret(), e.value)
if secret := e.getSecret(); secret != "" {
decrypt, err := Decrypt(e.value, secret)
return string(decrypt), err
Expand Down Expand Up @@ -134,7 +133,7 @@ func (e *String) SetValue(value string) (err error) {
return nil
}

func (e *String) SetSecret(secret string) {
func (e *String) UpdateSecret(secret string) {
plain, err := e.UnsafeString()
if err != nil {
return
Expand All @@ -147,6 +146,10 @@ func (e *String) SetSecret(secret string) {
e.secret = secret
}

func (e *String) SetSecret(secret string) {
e.secret = secret
}

// Scan implements the Scanner interface.
func (e *String) Scan(value any) error {
switch vt := value.(type) {
Expand Down

0 comments on commit f2918fa

Please sign in to comment.