summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/Crypto/Polyfill/Key.php
blob: 49d0c698804dd8f2aabfe2887f2d7bc64ebf0e06 (plain)
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
<?php
namespace Aws\Crypto\Polyfill;

/**
 * Class Key
 *
 * Wraps a string to keep it hidden from stack traces.
 *
 * @package Aws\Crypto\Polyfill
 */
class Key
{
    /**
     * @var string $internalString
     */
    private $internalString;

    /**
     * Hide contents of 
     *
     * @return array
     */
    public function __debugInfo()
    {
        return [];
    }

    /**
     * Key constructor.
     * @param string $str
     */
    public function __construct($str)
    {
        $this->internalString = $str;
    }

    /**
     * Defense in depth:
     *
     * PHP 7.2 includes the Sodium cryptography library, which (among other things)
     * exposes a function called sodium_memzero() that we can use to zero-fill strings
     * to minimize the risk of sensitive cryptographic materials persisting in memory.
     *
     * If this function is not available, we XOR the string in-place with itself as a
     * best-effort attempt.
     */
    public function __destruct()
    {
        if (extension_loaded('sodium') && function_exists('sodium_memzero')) {
            try {
                \sodium_memzero($this->internalString);
            } catch (\SodiumException $ex) {
                // This is a best effort, but does not provide the same guarantees as sodium_memzero():
                $this->internalString ^= $this->internalString;
            }
        }
    }

    /**
     * @return string
     */
    public function get()
    {
        return $this->internalString;
    }

    /**
     * @return int
     */
    public function length()
    {
        if (\is_callable('\\mb_strlen')) {
            return (int) \mb_strlen($this->internalString, '8bit');
        }
        return (int) \strlen($this->internalString);
    }
}