Key.php 1.7 KB

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