Debian Codegraph @

openpgp/integration_tests/v2/utils_test.go

raw
1 package v2
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/rand"
7 mathrand "math/rand"
8 "strings"
9 "time"
10
11 "github.com/ProtonMail/go-crypto/openpgp/armor"
12 "github.com/ProtonMail/go-crypto/openpgp/packet"
13 "github.com/ProtonMail/go-crypto/openpgp/s2k"
14 openpgp "github.com/ProtonMail/go-crypto/openpgp/v2"
15 )
16
17 // This function produces random test vectors: generates keys according to the
18 // given settings, associates a random message for each key. It returns the
19 // test vectors.
20 func generateFreshTestVectors(num int) (vectors []testVector, err error) {
21 mathrand.Seed(time.Now().UTC().UnixNano())
22 for i := 0; i < num; i++ {
23 config := randConfig()
24 // Sample random email, comment, password and message
25 name, email, comment, password, message := randEntityData()
26
27 // Only for verbose display
28 v := "v4"
29 if config.V6() {
30 v = "v6"
31 }
32 pkAlgoNames := map[packet.PublicKeyAlgorithm]string{
33 packet.PubKeyAlgoRSA: "rsa_" + v,
34 packet.PubKeyAlgoEdDSA: "EdDSA_" + v,
35 packet.PubKeyAlgoEd25519: "ed25519_" + v,
36 packet.PubKeyAlgoEd448: "ed448_" + v,
37 packet.PubKeyAlgoMldsa65Ed25519: "mldsa_" + v,
38 packet.PubKeyAlgoSlhdsaShake128s: "slhdsa128s_" + v,
39 }
40
41 newVector := testVector{
42 config: config,
43 Name: pkAlgoNames[config.Algorithm],
44 Password: password,
45 Message: message,
46 }
47
48 // Generate keys
49 newEntity, errKG := openpgp.NewEntity(name, comment, email, config)
50 if errKG != nil {
51 panic(errKG)
52 }
53
54 // Encrypt private key of entity
55 rawPwd := []byte(password)
56 if newEntity.PrivateKey != nil && !newEntity.PrivateKey.Encrypted {
57 if err = newEntity.PrivateKey.Encrypt(rawPwd); err != nil {
58 panic(err)
59 }
60 }
61
62 // Encrypt subkeys of entity
63 for _, sub := range newEntity.Subkeys {
64 if sub.PrivateKey != nil && !sub.PrivateKey.Encrypted {
65 if err = sub.PrivateKey.Encrypt(rawPwd); err != nil {
66 panic(err)
67 }
68 }
69 }
70
71 w := bytes.NewBuffer(nil)
72 if err = newEntity.SerializePrivateWithoutSigning(w, nil); err != nil {
73 return nil, err
74 }
75
76 serialized := w.Bytes()
77
78 privateKey, _ := armorWithType(serialized, "PGP PRIVATE KEY BLOCK")
79 newVector.PrivateKey = privateKey
80 newVector.PublicKey, _ = publicKey(privateKey)
81 vectors = append(vectors, newVector)
82 }
83 return vectors, err
84 }
85
86 // armorWithType make bytes input to armor format
87 func armorWithType(input []byte, armorType string) (string, error) {
88 var b bytes.Buffer
89 w, err := armor.EncodeWithChecksumOption(&b, armorType, nil, false)
90 if err != nil {
91 return "", err
92 }
93 if _, err = w.Write(input); err != nil {
94 return "", err
95 }
96 if err := w.Close(); err != nil {
97 return "", err
98 }
99 return b.String(), nil
100 }
101
102 func publicKey(privateKey string) (string, error) {
103 privKeyReader := strings.NewReader(privateKey)
104 entries, err := openpgp.ReadArmoredKeyRing(privKeyReader)
105 if err != nil {
106 return "", err
107 }
108
109 var outBuf bytes.Buffer
110 for _, e := range entries {
111 err := e.Serialize(&outBuf)
112 if err != nil {
113 return "", err
114 }
115 }
116
117 outString, err := armorWithType(outBuf.Bytes(), "PGP PUBLIC KEY BLOCK")
118 if err != nil {
119 return "", err
120 }
121
122 return outString, nil
123 }
124
125 var runes = []rune("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKMNOPQRSTUVWXYZ.@-_:;?/!#$%^&*{}[]'\"+~()<>")
126
127 func randName() string {
128 firstName := make([]rune, 8)
129 lastName := make([]rune, 8)
130 nameRunes := runes[:26]
131
132 for i := range firstName {
133 firstName[i] = nameRunes[mathrand.Intn(len(nameRunes))]
134 }
135
136 for i := range lastName {
137 lastName[i] = nameRunes[mathrand.Intn(len(nameRunes))]
138 }
139
140 return string(firstName) + " " + string(lastName)
141 }
142
143 func randFileHints() *openpgp.FileHints {
144 fileNameRunes := runes[:66]
145 fileName := make([]rune, 1+mathrand.Intn(255))
146 for i := range fileName {
147 fileName[i] = fileNameRunes[mathrand.Intn(len(fileNameRunes))]
148 }
149
150 return &openpgp.FileHints{
151 IsUTF8: mathrand.Intn(2) == 0,
152 FileName: string(fileName),
153 ModTime: time.Now(),
154 }
155 }
156
157 func randEmail() string {
158 address := make([]rune, 20)
159 addressRunes := runes[:38]
160 domain := make([]rune, 5)
161 domainRunes := runes[:36]
162 ext := make([]rune, 3)
163 for i := range address {
164 address[i] = addressRunes[mathrand.Intn(len(addressRunes))]
165 }
166 for i := range domain {
167 domain[i] = domainRunes[mathrand.Intn(len(domainRunes))]
168 }
169 for i := range ext {
170 ext[i] = domainRunes[mathrand.Intn(len(domainRunes))]
171 }
172 email := string(address) + "@" + string(domain) + "." + string(ext)
173 return email
174 }
175
176 // Comment does not allow the following characters: ()<>\x00
177 func randComment() string {
178 comment := make([]rune, 140)
179 commentRunes := runes[:84]
180 for i := range comment {
181 comment[i] = commentRunes[mathrand.Intn(len(commentRunes))]
182 }
183 return string(comment)
184 }
185
186 func randPassword() string {
187 maxPasswordLength := 64
188 password := make([]rune, mathrand.Intn(maxPasswordLength-1)+1)
189 for i := range password {
190 password[i] = runes[mathrand.Intn(len(runes))]
191 }
192 return string(password)
193 }
194
195 func randMessage() string {
196 maxMessageLength := 1 << 20
197 message := make([]byte, 1+mathrand.Intn(maxMessageLength-1))
198 if _, err := rand.Read(message); err != nil {
199 panic(err)
200 }
201 return string(message)
202 }
203
204 // Change one char of the input
205 func corrupt(input string) string {
206 if input == "" {
207 return string(runes[mathrand.Intn(len(runes))])
208 }
209 output := []rune(input)
210 for string(output) == input {
211 output[mathrand.Intn(len(output))] = runes[mathrand.Intn(len(runes))]
212 }
213 return string(output)
214 }
215
216 func randEntityData() (string, string, string, string, string) {
217 return randName(), randEmail(), randComment(), randPassword(), randMessage()
218 }
219
220 func randConfig() *packet.Config {
221 hashes := []crypto.Hash{
222 crypto.SHA256,
223 }
224 hash := hashes[mathrand.Intn(len(hashes))]
225
226 ciphers := []packet.CipherFunction{
227 packet.CipherAES256,
228 }
229 ciph := ciphers[mathrand.Intn(len(ciphers))]
230
231 compAlgos := []packet.CompressionAlgo{
232 packet.CompressionNone,
233 packet.CompressionZIP,
234 packet.CompressionZLIB,
235 }
236 compAlgo := compAlgos[mathrand.Intn(len(compAlgos))]
237
238 pkAlgos := []packet.PublicKeyAlgorithm{
239 packet.PubKeyAlgoRSA,
240 packet.PubKeyAlgoEdDSA,
241 packet.PubKeyAlgoEd25519,
242 packet.PubKeyAlgoEd448,
243 packet.PubKeyAlgoMldsa65Ed25519,
244 packet.PubKeyAlgoSlhdsaShake128s,
245 }
246 pkAlgo := pkAlgos[mathrand.Intn(len(pkAlgos))]
247
248 aeadModes := []packet.AEADMode{
249 packet.AEADModeOCB,
250 packet.AEADModeEAX,
251 packet.AEADModeGCM,
252 }
253 var aeadConf = packet.AEADConfig{
254 DefaultMode: aeadModes[mathrand.Intn(len(aeadModes))],
255 }
256
257 var rsaBits int
258 if pkAlgo == packet.PubKeyAlgoRSA {
259 switch mathrand.Int() % 4 {
260 case 0:
261 rsaBits = 2048
262 case 1:
263 rsaBits = 3072
264 case 2:
265 rsaBits = 4096
266 default:
267 rsaBits = 0
268 }
269 }
270
271 level := mathrand.Intn(11) - 1
272 compConf := &packet.CompressionConfig{Level: level}
273
274 var v6 bool
275 if pkAlgo == packet.PubKeyAlgoMldsa65Ed25519 || pkAlgo == packet.PubKeyAlgoSlhdsaShake128s {
276 v6 = true
277 } else if mathrand.Int()%2 == 0 {
278 v6 = true
279 if pkAlgo == packet.PubKeyAlgoEdDSA {
280 pkAlgo = packet.PubKeyAlgoEd25519
281 }
282 }
283
284 var s2kConf *s2k.Config
285 if mathrand.Int()%2 == 0 {
286 s2kConf = &s2k.Config{
287 S2KMode: s2k.IteratedSaltedS2K,
288 Hash: hash,
289 S2KCount: 1024 + mathrand.Intn(65010689),
290 }
291 } else {
292 s2kConf = &s2k.Config{
293 S2KMode: s2k.Argon2S2K,
294 }
295 }
296
297 return &packet.Config{
298 V6Keys: v6,
299 Rand: rand.Reader,
300 DefaultHash: hash,
301 DefaultCipher: ciph,
302 DefaultCompressionAlgo: compAlgo,
303 CompressionConfig: compConf,
304 S2KConfig: s2kConf,
305 RSABits: rsaBits,
306 Algorithm: pkAlgo,
307 AEADConfig: &aeadConf,
308 RejectPublicKeyAlgorithms: map[packet.PublicKeyAlgorithm]bool{},
309 RejectCurves: map[packet.Curve]bool{},
310 MinRSABits: 512,
311 }
312 }