• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 20411118016

21 Dec 2025 02:17PM UTC coverage: 84.514% (-0.02%) from 84.53%
20411118016

Pull #9853

github

web-flow
Merge 97e32f40a into 23b64e61a
Pull Request #9853: feat(encryption): Add previous keys fallback feature

43 of 53 new or added lines in 4 files covered. (81.13%)

11 existing lines in 3 files now uncovered.

21518 of 25461 relevant lines covered (84.51%)

196.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.0
/system/Encryption/Handlers/SodiumHandler.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Encryption\Handlers;
15

16
use CodeIgniter\Encryption\Exceptions\EncryptionException;
17

18
/**
19
 * SodiumHandler uses libsodium in encryption.
20
 *
21
 * @see https://github.com/jedisct1/libsodium/issues/392
22
 * @see \CodeIgniter\Encryption\Handlers\SodiumHandlerTest
23
 */
24
class SodiumHandler extends BaseHandler
25
{
26
    /**
27
     * Starter key
28
     *
29
     * @var string|null Null is used for buffer cleanup.
30
     */
31
    protected $key = '';
32

33
    /**
34
     * List of previous keys for fallback decryption.
35
     */
36
    protected string $previousKeys = '';
37

38
    /**
39
     * Block size for padding message.
40
     *
41
     * @var int
42
     */
43
    protected $blockSize = 16;
44

45
    /**
46
     * {@inheritDoc}
47
     */
48
    public function encrypt($data, $params = null)
49
    {
50
        $this->parseParams($params);
6✔
51

52
        if (empty($this->key)) {
6✔
53
            throw EncryptionException::forNeedsStarterKey();
1✔
54
        }
55

56
        // create a nonce for this operation
57
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes
5✔
58

59
        // add padding before we encrypt the data
60
        if ($this->blockSize <= 0) {
5✔
61
            throw EncryptionException::forEncryptionFailed();
1✔
62
        }
63

64
        $data = sodium_pad($data, $this->blockSize);
4✔
65

66
        // encrypt message and combine with nonce
67
        $ciphertext = $nonce . sodium_crypto_secretbox($data, $nonce, $this->key);
4✔
68

69
        // cleanup buffers
70
        sodium_memzero($data);
4✔
71
        sodium_memzero($this->key);
4✔
72

73
        return $ciphertext;
4✔
74
    }
75

76
    /**
77
     * {@inheritDoc}
78
     */
79
    public function decrypt($data, $params = null)
80
    {
81
        $this->parseParams($params);
4✔
82

83
        if (empty($this->key)) {
4✔
84
            throw EncryptionException::forNeedsStarterKey();
1✔
85
        }
86

87
        $result = false;
3✔
88

89
        try {
90
            $result = $this->decryptWithKey($data, $this->key);
3✔
91
            sodium_memzero($this->key);
1✔
92
        } catch (EncryptionException $e) {
2✔
93
            $exception = $e;
2✔
94
            sodium_memzero($this->key);
2✔
95
        }
96

97
        if ($result === false && $this->previousKeys !== '') {
3✔
NEW
98
            foreach (explode(',', $this->previousKeys) as $previousKey) {
×
99
                try {
NEW
100
                    $result = $this->decryptWithKey($data, $previousKey);
×
NEW
101
                    if (isset($result)) {
×
NEW
102
                        return $result;
×
103
                    }
NEW
104
                } catch (EncryptionException) {
×
105
                    // Try next key
106
                }
107
            }
108
        }
109

110
        if (isset($exception)) {
3✔
111
            throw $exception;
2✔
112
        }
113

114
        return $result;
1✔
115
    }
116

117
    /**
118
     * Decrypt the data with the provided key
119
     *
120
     * @param string $data
121
     * @param string $key
122
     *
123
     * @return string
124
     *
125
     * @throws EncryptionException
126
     */
127
    protected function decryptWithKey($data, $key)
128
    {
129
        if (mb_strlen($data, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
3✔
130
            // message was truncated
131
            throw EncryptionException::forAuthenticationFailed();
1✔
132
        }
133

134
        // Extract info from encrypted data
135
        $nonce      = self::substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
2✔
136
        $ciphertext = self::substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
2✔
137

138
        // decrypt data
139
        $data = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
2✔
140

141
        if ($data === false) {
2✔
142
            // message was tampered in transit
UNCOV
143
            throw EncryptionException::forAuthenticationFailed(); // @codeCoverageIgnore
×
144
        }
145

146
        // remove extra padding during encryption
147
        if ($this->blockSize <= 0) {
2✔
148
            throw EncryptionException::forAuthenticationFailed();
1✔
149
        }
150

151
        $data = sodium_unpad($data, $this->blockSize);
1✔
152

153
        // cleanup buffers
154
        sodium_memzero($ciphertext);
1✔
155

156
        return $data;
1✔
157
    }
158

159
    /**
160
     * Parse the $params before doing assignment.
161
     *
162
     * @param array|string|null $params
163
     *
164
     * @return void
165
     *
166
     * @throws EncryptionException If key is empty
167
     */
168
    protected function parseParams($params)
169
    {
170
        if ($params === null) {
6✔
171
            return;
5✔
172
        }
173

174
        if (is_array($params)) {
4✔
175
            if (isset($params['key'])) {
2✔
176
                $this->key = $params['key'];
2✔
177
            }
178

179
            if (isset($params['blockSize'])) {
2✔
180
                $this->blockSize = $params['blockSize'];
2✔
181
            }
182

183
            return;
2✔
184
        }
185

186
        $this->key = (string) $params;
2✔
187
    }
188
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc