|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace APP\plugins\generic\dataverse\classes; |
| 4 | + |
| 5 | +use PKP\config\Config; |
| 6 | +use Illuminate\Encryption\Encrypter; |
| 7 | +use Exception; |
| 8 | + |
| 9 | +class DataEncryption |
| 10 | +{ |
| 11 | + private const ENCRYPTION_CIPHER = 'aes-256-cbc'; |
| 12 | + private const BASE64_PREFIX = 'base64:'; |
| 13 | + |
| 14 | + public function secretConfigExists(): bool |
| 15 | + { |
| 16 | + try { |
| 17 | + $this->getSecretFromConfig(); |
| 18 | + } catch (Exception $e) { |
| 19 | + return false; |
| 20 | + } |
| 21 | + return true; |
| 22 | + } |
| 23 | + |
| 24 | + private function getSecretFromConfig(): string |
| 25 | + { |
| 26 | + $secret = Config::getVar('security', 'api_key_secret'); |
| 27 | + if ($secret === "") { |
| 28 | + throw new Exception("Dataverse Error: A secret must be set in the config file ('api_key_secret') so that keys can be encrypted and decrypted"); |
| 29 | + } |
| 30 | + |
| 31 | + return $this->normalizeSecret($secret); |
| 32 | + } |
| 33 | + |
| 34 | + private function normalizeSecret(string $secret): string |
| 35 | + { |
| 36 | + return hash('sha256', $secret, true); |
| 37 | + } |
| 38 | + |
| 39 | + public function textIsEncrypted(string $text): bool |
| 40 | + { |
| 41 | + if (!str_starts_with($text, self::BASE64_PREFIX)) { |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + try { |
| 46 | + $this->decryptString($text); |
| 47 | + return true; |
| 48 | + } catch (Exception $e) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public function encryptString(string $plainText): string |
| 54 | + { |
| 55 | + $secret = $this->getSecretFromConfig(); |
| 56 | + $encrypter = new Encrypter($secret, self::ENCRYPTION_CIPHER); |
| 57 | + |
| 58 | + try { |
| 59 | + $encryptedString = $encrypter->encrypt($plainText); |
| 60 | + } catch (Exception $e) { |
| 61 | + throw new Exception("DEIA Survey - Failed to encrypt string"); |
| 62 | + } |
| 63 | + |
| 64 | + return self::BASE64_PREFIX . base64_encode($encryptedString); |
| 65 | + } |
| 66 | + |
| 67 | + public function decryptString(string $encryptedText): string |
| 68 | + { |
| 69 | + $secret = $this->getSecretFromConfig(); |
| 70 | + $encrypter = new Encrypter($secret, self::ENCRYPTION_CIPHER); |
| 71 | + |
| 72 | + $encryptedText = str_replace(self::BASE64_PREFIX, '', $encryptedText); |
| 73 | + $payload = base64_decode($encryptedText); |
| 74 | + |
| 75 | + try { |
| 76 | + $decryptedString = $encrypter->decrypt($payload); |
| 77 | + } catch (Exception $e) { |
| 78 | + throw new Exception("Dataverse Error: Failed to decrypt string"); |
| 79 | + } |
| 80 | + |
| 81 | + return $decryptedString; |
| 82 | + } |
| 83 | +} |
0 commit comments