/
message.go
272 lines (237 loc) · 7.35 KB
/
message.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package crypto
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"time"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
pgpErrors "golang.org/x/crypto/openpgp/errors"
"golang.org/x/crypto/openpgp/packet"
armorUtils "github.com/ProtonMail/gopenpgp/armor"
"github.com/ProtonMail/gopenpgp/constants"
"github.com/ProtonMail/gopenpgp/internal"
"github.com/ProtonMail/gopenpgp/models"
)
// DecryptMessageStringKey decrypts encrypted message use private key (string)
// encryptedText : string armored encrypted
// privateKey : armored private use to decrypt message
// passphrase : match with private key to decrypt message
func (pgp *GopenPGP) DecryptMessageStringKey(
encryptedText, privateKey, passphrase string,
) (string, error) {
privKeyRaw, err := armorUtils.Unarmor(privateKey)
if err != nil {
return "", err
}
privKeyReader := bytes.NewReader(privKeyRaw)
privKeyEntries, err := openpgp.ReadKeyRing(privKeyReader)
if err != nil {
return "", err
}
return pgp.DecryptMessage(encryptedText, &KeyRing{entities: privKeyEntries}, passphrase)
}
// DecryptMessage decrypts encrypted string using keyring
// encryptedText : string armored encrypted
// privateKey : keyring with private key to decrypt message, could be multiple keys
// passphrase : match with private key to decrypt message
func (pgp *GopenPGP) DecryptMessage(encryptedText string, privateKey *KeyRing, passphrase string) (string, error) {
md, err := decryptCore(encryptedText, nil, privateKey, passphrase, pgp.getTimeGenerator())
if err != nil {
return "", err
}
decrypted := md.UnverifiedBody
b, err := ioutil.ReadAll(decrypted)
if err != nil {
return "", err
}
return string(b), nil
}
func decryptCore(
encryptedText string, additionalEntries openpgp.EntityList,
privKey *KeyRing, passphrase string,
timeFunc func() time.Time,
) (*openpgp.MessageDetails, error) {
rawPwd := []byte(passphrase)
if err := privKey.Unlock(rawPwd); err != nil {
err = fmt.Errorf("gopenpgp: cannot decrypt passphrase: %v", err)
return nil, err
}
privKeyEntries := privKey.entities
if additionalEntries != nil {
privKeyEntries = append(privKeyEntries, additionalEntries...)
}
encryptedio, err := internal.Unarmor(encryptedText)
if err != nil {
return nil, err
}
config := &packet.Config{Time: timeFunc}
md, err := openpgp.ReadMessage(encryptedio.Body, privKeyEntries, nil, config)
return md, err
}
// DecryptMessageVerify decrypts message and verify the signature
// encryptedText: string armored encrypted
// verifierKey []byte: unarmored verifier keys
// privateKeyRing []byte: unarmored private key to decrypt. could be multiple
// passphrase: match with private key to decrypt message
func (pgp *GopenPGP) DecryptMessageVerify(
encryptedText string, verifierKey, privateKeyRing *KeyRing,
passphrase string, verifyTime int64,
) (*models.DecryptSignedVerify, error) {
out := &models.DecryptSignedVerify{}
out.Verify = failed
var verifierEntries openpgp.EntityList
if len(verifierKey.entities) == 0 {
out.Verify = noVerifier
}
md, err := decryptCore(
encryptedText,
verifierEntries,
privateKeyRing,
passphrase,
func() time.Time { return time.Unix(0, 0) }) // TODO: I doubt this time is correct
if err != nil {
return nil, err
}
decrypted := md.UnverifiedBody
b, err := ioutil.ReadAll(decrypted)
if err != nil {
return nil, err
}
processSignatureExpiration(md, verifyTime)
out.Plaintext = string(b)
if md.IsSigned {
if md.SignedBy != nil {
if len(verifierKey.entities) > 0 {
matches := verifierKey.entities.KeysById(md.SignedByKeyId)
if len(matches) > 0 {
if md.SignatureError == nil {
out.Verify = ok
} else {
out.Message = md.SignatureError.Error()
out.Verify = failed
}
}
} else {
out.Verify = noVerifier
}
} else {
out.Verify = noVerifier
}
} else {
out.Verify = notSigned
}
return out, nil
}
// processSignatureExpiration handles signature time verification manually, so we can add a margin to the
// creationTime check.
func processSignatureExpiration(md *openpgp.MessageDetails, verifyTime int64) {
if md.SignatureError == pgpErrors.ErrSignatureExpired {
if verifyTime > 0 {
created := md.Signature.CreationTime.Unix()
expires := int64(math.MaxInt64)
if md.Signature.SigLifetimeSecs != nil {
expires = int64(*md.Signature.SigLifetimeSecs) + created
}
if created-internal.CreationTimeOffset <= verifyTime && verifyTime <= expires {
md.SignatureError = nil
}
} else {
// verifyTime = 0: time check disabled, everything is okay
md.SignatureError = nil
}
}
}
// EncryptMessageWithPassword encrypts a plain text to pgp message with a password
// plainText string: clear text
// output string: armored pgp message
func (pgp *GopenPGP) EncryptMessageWithPassword(plainText string, password string) (string, error) {
var outBuf bytes.Buffer
w, err := armor.Encode(&outBuf, constants.PGPMessageHeader, internal.ArmorHeaders)
if err != nil {
return "", err
}
config := &packet.Config{Time: pgp.getTimeGenerator()}
plaintext, err := openpgp.SymmetricallyEncrypt(w, []byte(password), nil, config)
if err != nil {
return "", err
}
message := []byte(plainText)
_, err = plaintext.Write(message)
if err != nil {
return "", err
}
err = plaintext.Close()
if err != nil {
return "", err
}
w.Close()
return outBuf.String(), nil
}
// EncryptMessage encrypts message with unarmored public key, if pass private key and passphrase will also sign
// the message
// publicKey : bytes unarmored public key
// plainText : the input
// privateKey : optional required when you want to sign
// passphrase : optional required when you pass the private key and this passphrase should decrypt the private key
// trim : bool true if need to trim new lines
func (pgp *GopenPGP) EncryptMessage(
plainText string, publicKey, privateKey *KeyRing,
passphrase string, trim bool,
) (string, error) {
if trim {
plainText = internal.TrimNewlines(plainText)
}
var outBuf bytes.Buffer
w, err := armor.Encode(&outBuf, constants.PGPMessageHeader, internal.ArmorHeaders)
if err != nil {
return "", err
}
var signEntity *openpgp.Entity
if len(passphrase) > 0 && len(privateKey.entities) > 0 {
var err error
signEntity, err = privateKey.GetSigningEntity(passphrase)
if err != nil {
return "", err
}
}
ew, err := EncryptCore(w, publicKey.entities, signEntity, "", false, pgp.getTimeGenerator())
if err != nil {
return "", err
}
_, err = ew.Write([]byte(plainText))
ew.Close()
w.Close()
return outBuf.String(), err
}
// DecryptMessageWithPassword decrypts a pgp message with a password
// encrypted string : armored pgp message
// output string : clear text
func (pgp *GopenPGP) DecryptMessageWithPassword(encrypted string, password string) (string, error) {
encryptedio, err := internal.Unarmor(encrypted)
if err != nil {
return "", err
}
firstTimeCalled := true
var prompt = func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if firstTimeCalled {
firstTimeCalled = false
return []byte(password), nil
}
return nil, errors.New("password incorrect")
}
config := &packet.Config{Time: pgp.getTimeGenerator()}
md, err := openpgp.ReadMessage(encryptedio.Body, nil, prompt, config)
if err != nil {
return "", err
}
messageBuf := bytes.NewBuffer(nil)
_, err = io.Copy(messageBuf, md.UnverifiedBody)
if err != nil {
return "", err
}
return messageBuf.String(), nil
}