Key.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Aws\Crypto\Polyfill;
  3. /**
  4. * Class Key
  5. *
  6. * Wraps a string to keep it hidden from stack traces.
  7. *
  8. * @package Aws\Crypto\Polyfill
  9. */
  10. class Key
  11. {
  12. /**
  13. * @var string $internalString
  14. */
  15. private $internalString;
  16. /**
  17. * Hide contents of
  18. *
  19. * @return array
  20. */
  21. public function __debugInfo()
  22. {
  23. return [];
  24. }
  25. /**
  26. * Key constructor.
  27. * @param string $str
  28. */
  29. public function __construct($str)
  30. {
  31. $this->internalString = $str;
  32. }
  33. /**
  34. * Defense in depth:
  35. *
  36. * PHP 7.2 includes the Sodium cryptography library, which (among other things)
  37. * exposes a function called sodium_memzero() that we can use to zero-fill strings
  38. * to minimize the risk of sensitive cryptographic materials persisting in memory.
  39. *
  40. * If this function is not available, we XOR the string in-place with itself as a
  41. * best-effort attempt.
  42. */
  43. public function __destruct()
  44. {
  45. if (extension_loaded('sodium') && function_exists('sodium_memzero')) {
  46. try {
  47. \sodium_memzero($this->internalString);
  48. } catch (\SodiumException $ex) {
  49. // This is a best effort, but does not provide the same guarantees as sodium_memzero():
  50. $this->internalString ^= $this->internalString;
  51. }
  52. }
  53. }
  54. /**
  55. * @return string
  56. */
  57. public function get()
  58. {
  59. return $this->internalString;
  60. }
  61. /**
  62. * @return int
  63. */
  64. public function length()
  65. {
  66. if (\is_callable('\\mb_strlen')) {
  67. return (int) \mb_strlen($this->internalString, '8bit');
  68. }
  69. return (int) \strlen($this->internalString);
  70. }
  71. }