-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
64 lines (52 loc) · 1.75 KB
/
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
//
// Copyright (C) 2020 Dmitry Kolesnikov
//
// This file may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
// https://github.com/fogfish/cryptex
//
package cryptex
import (
"encoding/json"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/fogfish/cryptex/cipher"
)
// String is an alias built-in `string`. It shall be used as a container for sensitive
// data. Its sensitive value is not assignable to variable of type `string`. You have
// to either use helper method `PlainText` or cast it to string. This makes a simple
// protection against accidental leakage.
type String string
// UnmarshalJSON implements automatic decryption of data
func (value *String) UnmarshalJSON(b []byte) (err error) {
var cryptotext string
if err = json.Unmarshal(b, &cryptotext); err != nil {
return
}
text, err := cipher.Default.Decrypt(cryptotext)
if err != nil {
return
}
*value = String(text)
return
}
// MarshalJSON implements automatic encryption of sensitive strings during data marshalling.
func (value String) MarshalJSON() (bytes []byte, err error) {
text, err := cipher.Default.Encrypt([]byte(value))
if err != nil {
return
}
return json.Marshal(text)
}
// MarshalDynamoDBAttributeValue implements automatic encryption of sensitive strings during data marshalling.
func (value String) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) (err error) {
av.B, err = value.MarshalJSON()
return
}
// UnmarshalDynamoDBAttributeValue implements automatic decryption of data
func (value *String) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
return value.UnmarshalJSON(av.B)
}
// PlainText returns plain text value
func (value String) PlainText() string {
return string(value)
}