sjcl.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 0.22
  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)) return false;
  36. $decoded = (array) $decoded;
  37. // Make sure no additionnal keys were added.
  38. if (
  39. count(array_keys($decoded)) != count($accepted_keys)
  40. ) return false;
  41. // Make sure required fields are present and contain base64 data.
  42. foreach($accepted_keys as $k)
  43. {
  44. if (!array_key_exists($k, $decoded)) return false;
  45. }
  46. // Make sure some fields are base64 data.
  47. if (!base64_decode($decoded['iv'], true)) return false;
  48. if (!base64_decode($decoded['salt'], true)) return false;
  49. if (!($ct = base64_decode($decoded['ct'], true))) return false;
  50. // Make sure some fields have a reasonable size.
  51. if (strlen($decoded['iv']) > 24) return false;
  52. if (strlen($decoded['salt']) > 14) return false;
  53. // Make sure some fields contain no unsupported values.
  54. if (!(is_int($decoded['v']) || is_float($decoded['v'])) || (float) $decoded['v'] < 1) return false;
  55. if (!is_int($decoded['iter']) || $decoded['iter'] <= 100) return false;
  56. if (!in_array($decoded['ks'], array(128, 192, 256), true)) return false;
  57. if (!in_array($decoded['ts'], array(64, 96, 128), true)) return false;
  58. if (!in_array($decoded['mode'], array('ccm', 'ocb2', 'gcm'), true)) return false;
  59. if ($decoded['cipher'] !== 'aes') return false;
  60. // Reject data if entropy is too low
  61. if (strlen($ct) > strlen(gzdeflate($ct))) return false;
  62. return true;
  63. }
  64. }