Debian Codegraph @

crypto/utils/utils.go

raw
1 // Copyright (c) 2020 Nikos Filippakis
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package utils
8
9 import (
10 "crypto/aes"
11 "crypto/cipher"
12 "crypto/hmac"
13 "crypto/sha256"
14 "crypto/sha512"
15 "encoding/base64"
16 "math/rand"
17 "strings"
18
19 "golang.org/x/crypto/hkdf"
20 "golang.org/x/crypto/pbkdf2"
21
22 "maunium.net/go/mautrix/util/base58"
23 )
24
25 const (
26 // AESCTRKeyLength is the length of the AES256-CTR key used.
27 AESCTRKeyLength = 32
28 // AESCTRIVLength is the length of the AES256-CTR IV used.
29 AESCTRIVLength = 16
30 // HMACKeyLength is the length of the HMAC key used.
31 HMACKeyLength = 32
32 // SHAHashLength is the length of the SHA hash used.
33 SHAHashLength = 32
34 )
35
36 // XorA256CTR encrypts the input with the keystream generated by the AES256-CTR algorithm with the given arguments.
37 func XorA256CTR(source []byte, key [AESCTRKeyLength]byte, iv [AESCTRIVLength]byte) []byte {
38 block, _ := aes.NewCipher(key[:])
39 cipher.NewCTR(block, iv[:]).XORKeyStream(source, source)
40 return source
41 }
42
43 // GenAttachmentA256CTR generates a new random AES256-CTR key and IV suitable for encrypting attachments.
44 func GenAttachmentA256CTR() (key [AESCTRKeyLength]byte, iv [AESCTRIVLength]byte) {
45 _, err := rand.Read(key[:])
46 if err != nil {
47 panic(err)
48 }
49
50 // The last 8 bytes of the IV act as the counter in AES-CTR, which means they're left empty here
51 _, err = rand.Read(iv[:8])
52 if err != nil {
53 panic(err)
54 }
55 return
56 }
57
58 // GenA256CTRIV generates a random IV for AES256-CTR with the last bit set to zero.
59 func GenA256CTRIV() (iv [AESCTRIVLength]byte) {
60 _, err := rand.Read(iv[:])
61 if err != nil {
62 panic(err)
63 }
64 iv[8] &= 0x7F
65 return
66 }
67
68 // DeriveKeysSHA256 derives an AES and a HMAC key from the given recovery key.
69 func DeriveKeysSHA256(key []byte, name string) ([AESCTRKeyLength]byte, [HMACKeyLength]byte) {
70 var zeroBytes [32]byte
71
72 derivedHkdf := hkdf.New(sha256.New, key[:], zeroBytes[:], []byte(name))
73
74 var aesKey [AESCTRKeyLength]byte
75 var hmacKey [HMACKeyLength]byte
76 derivedHkdf.Read(aesKey[:])
77 derivedHkdf.Read(hmacKey[:])
78
79 return aesKey, hmacKey
80 }
81
82 // PBKDF2SHA512 generates a key of the given bit-length using the given passphrase, salt and iteration count.
83 func PBKDF2SHA512(password []byte, salt []byte, iters int, keyLenBits int) []byte {
84 return pbkdf2.Key(password, salt, iters, keyLenBits/8, sha512.New)
85 }
86
87 // DecodeBase58RecoveryKey recovers the secret storage from a recovery key.
88 func DecodeBase58RecoveryKey(recoveryKey string) []byte {
89 noSpaces := strings.ReplaceAll(recoveryKey, " ", "")
90 decoded := base58.Decode(noSpaces)
91 if len(decoded) != AESCTRKeyLength+3 { // AESCTRKeyLength bytes key and 3 bytes prefix / parity
92 return nil
93 }
94 var parity byte
95 for _, b := range decoded[:34] {
96 parity ^= b
97 }
98 if parity != decoded[34] || decoded[0] != 0x8B || decoded[1] != 1 {
99 return nil
100 }
101 return decoded[2:34]
102 }
103
104 // EncodeBase58RecoveryKey recovers the secret storage from a recovery key.
105 func EncodeBase58RecoveryKey(key []byte) string {
106 var inputBytes [35]byte
107 copy(inputBytes[2:34], key[:])
108 inputBytes[0] = 0x8B
109 inputBytes[1] = 1
110
111 var parity byte
112 for _, b := range inputBytes[:34] {
113 parity ^= b
114 }
115 inputBytes[34] = parity
116 recoveryKey := base58.Encode(inputBytes[:])
117
118 var spacedKey string
119 for i, c := range recoveryKey {
120 if i > 0 && i%4 == 0 {
121 spacedKey += " "
122 }
123 spacedKey += string(c)
124 }
125 return spacedKey
126 }
127
128 // HMACSHA256B64 calculates the base64 of the SHA256 hmac of the input with the given key.
129 func HMACSHA256B64(input []byte, hmacKey [HMACKeyLength]byte) string {
130 h := hmac.New(sha256.New, hmacKey[:])
131 h.Write(input)
132 return base64.StdEncoding.EncodeToString(h.Sum(nil))
133 }