Crypt.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Utils;
  3. use App\Utils\Config;
  4. use Spatie\Crypto\Rsa\KeyPair;
  5. use Spatie\Crypto\Rsa\PrivateKey;
  6. use Spatie\Crypto\Rsa\PublicKey;
  7. use Exception;
  8. class Crypt
  9. {
  10. private const configFilename = 'crypt';
  11. private const privateKeyFilename = 'private.key';
  12. private const publicKeyFilename = 'public.key';
  13. private const privateKeyBits = 4096;
  14. private $userPathKeys;
  15. private $privateKey;
  16. private $publicKey;
  17. public function __construct(string $uuid)
  18. {
  19. $this->mount($uuid);
  20. }
  21. private function mount(string $uuid)
  22. {
  23. $config = Config::getFromFilename(self::configFilename);
  24. $pathKeys = $config['path_keys'];
  25. if (!is_dir($pathKeys)) {
  26. throw new Exception(sprintf('Crypt path keys "%s" cannot be found.', $pathKeys));
  27. }
  28. $this->userPathKeys = sprintf('%s/%s/', realpath($pathKeys), $uuid);
  29. // Crea el directorio de las llaves de cifrado del usuario.
  30. is_dir($this->userPathKeys) || mkdir($this->userPathKeys);
  31. $pathToPrivateKey = $this->userPathKeys . self::privateKeyFilename;
  32. $pathToPublicKey = $this->userPathKeys . self::publicKeyFilename;
  33. // Genera las llaves de cifrado si no existen.
  34. if (!is_file($pathToPrivateKey) && !is_file($pathToPublicKey)) {
  35. (new KeyPair())->generate($pathToPrivateKey, $pathToPublicKey);
  36. }
  37. $this->privateKey = PrivateKey::fromFile($pathToPrivateKey);
  38. $this->publicKey = PublicKey::fromFile($pathToPublicKey);
  39. }
  40. /*
  41. * Encripta un string.
  42. */
  43. public function encrypt(string $data)
  44. {
  45. $encryptedData = '';
  46. foreach (str_split($data, self::privateKeyBits / 8 - 64) as $part) {
  47. $encryptedData .= $this->publicKey->encrypt($part);
  48. }
  49. return base64_encode($encryptedData);
  50. }
  51. /*
  52. * Desencripta un string.
  53. */
  54. public function decrypt(string $encryptedData)
  55. {
  56. $data = '';
  57. foreach (str_split(base64_decode($encryptedData), self::privateKeyBits * 128 / 1024) as $part) {
  58. $data .= $this->privateKey->decrypt($part);
  59. }
  60. return $data;
  61. }
  62. /*
  63. * Obtiene el directorio de las llaves de cifrado del usuario.
  64. */
  65. public function getUserPathKeys()
  66. {
  67. return $this->userPathKeys;
  68. }
  69. }