Sjcl.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 1.2.1
  11. */
  12. namespace PrivateBin;
  13. /**
  14. * Sjcl
  15. *
  16. * Provides SJCL validation function.
  17. */
  18. class Sjcl
  19. {
  20. /**
  21. * SJCL validator
  22. *
  23. * Checks if a json string is a proper SJCL encrypted message.
  24. *
  25. * @access public
  26. * @static
  27. * @param string $encoded JSON
  28. * @return bool
  29. */
  30. public static function isValid($encoded)
  31. {
  32. $accepted_keys = array('iv', 'v', 'iter', 'ks', 'ts', 'mode', 'adata', 'cipher', 'salt', 'ct');
  33. // Make sure content is valid json
  34. $decoded = json_decode($encoded);
  35. if (is_null($decoded)) {
  36. return false;
  37. }
  38. $decoded = (array) $decoded;
  39. // Make sure no additionnal keys were added.
  40. if (
  41. count(array_keys($decoded)) != count($accepted_keys)
  42. ) {
  43. return false;
  44. }
  45. // Make sure required fields are present and contain base64 data.
  46. foreach ($accepted_keys as $k) {
  47. if (!array_key_exists($k, $decoded)) {
  48. return false;
  49. }
  50. }
  51. // Make sure some fields are base64 data.
  52. if (!base64_decode($decoded['iv'], true)) {
  53. return false;
  54. }
  55. if (!base64_decode($decoded['salt'], true)) {
  56. return false;
  57. }
  58. if (!($ct = base64_decode($decoded['ct'], true))) {
  59. return false;
  60. }
  61. // Make sure some fields have a reasonable size.
  62. if (strlen($decoded['iv']) > 24) {
  63. return false;
  64. }
  65. if (strlen($decoded['salt']) > 14) {
  66. return false;
  67. }
  68. // Make sure some fields contain no unsupported values.
  69. if (!(is_int($decoded['v']) || is_float($decoded['v'])) || (float) $decoded['v'] < 1) {
  70. return false;
  71. }
  72. if (!is_int($decoded['iter']) || $decoded['iter'] <= 100) {
  73. return false;
  74. }
  75. if (!in_array($decoded['ks'], array(128, 192, 256), true)) {
  76. return false;
  77. }
  78. if (!in_array($decoded['ts'], array(64, 96, 128), true)) {
  79. return false;
  80. }
  81. if (!in_array($decoded['mode'], array('ccm', 'ocb2', 'gcm'), true)) {
  82. return false;
  83. }
  84. if ($decoded['cipher'] !== 'aes') {
  85. return false;
  86. }
  87. // Reject data if entropy is too low
  88. if (strlen($ct) > strlen(gzdeflate($ct))) {
  89. return false;
  90. }
  91. return true;
  92. }
  93. }