|
78 | 78 | throw new \InvalidArgumentException('A private key path must be set to use this method.'); |
79 | 79 | } |
80 | 80 |
|
81 | | - if (false === ($private_key = openssl_get_privatekey($private_key_path))) { |
82 | | - throw new \InvalidArgumentException(sprintf('The path "%s" does not contain a private key.', $private_key_path)); |
83 | | - } |
| 81 | + $decrypt = function ($private_key_path) { |
| 82 | + if (false === ($private_key = openssl_get_privatekey($private_key_path))) { |
| 83 | + throw new \InvalidArgumentException(sprintf('The path "%s" does not contain a private key.', $private_key_path)); |
| 84 | + } |
84 | 85 |
|
85 | | - list($env_key_length, $iv_length, $pieces) = explode(',', $this->{{ property.name }}, 3); |
86 | | - $env_key = hex2bin(substr($pieces, 0, $env_key_length)); |
87 | | - $iv = hex2bin(substr($pieces, $env_key_length, $iv_length)); |
88 | | - $sealed_data = hex2bin(substr($pieces, $env_key_length + $iv_length)); |
| 86 | + list($env_key_length, $iv_length, $pieces) = explode(',', $this->{{ property.name }}, 3); |
| 87 | + $env_key = hex2bin(substr($pieces, 0, $env_key_length)); |
| 88 | + $iv = hex2bin(substr($pieces, $env_key_length, $iv_length)); |
| 89 | + $sealed_data = hex2bin(substr($pieces, $env_key_length + $iv_length)); |
89 | 90 |
|
90 | | - if (false === openssl_open($sealed_data, $open_data, $env_key, $private_key, 'AES256', $iv)) { |
91 | | - $err_string = ''; |
92 | | - while ($msg = openssl_error_string()) { |
93 | | - $err_string .= $msg . ' | '; |
| 91 | + if (false === openssl_open($sealed_data, $open_data, $env_key, $private_key, 'AES256', $iv)) { |
| 92 | + $err_string = ''; |
| 93 | + while ($msg = openssl_error_string()) { |
| 94 | + $err_string .= $msg . ' | '; |
| 95 | + } |
| 96 | + throw new \InvalidArgumentException(sprintf('openssl_open failed. Message: %s', $err_string)); |
94 | 97 | } |
95 | | - throw new \InvalidArgumentException(sprintf('openssl_open failed. Message: %s', $err_string)); |
96 | | - } |
97 | 98 |
|
98 | | - return $open_data; |
| 99 | + return $open_data; |
| 100 | + }; |
| 101 | + |
| 102 | + try { |
| 103 | + return $decrypt($private_key_path); |
| 104 | + } catch (\InvalidArgumentException $e) { |
| 105 | + if (false == ($fallback_private_key_path = KeyRegistry::getPrivateKeyPath('{{ property.encryptionAlias() }}_fallback'))) { |
| 106 | + throw $e; |
| 107 | + } |
| 108 | + |
| 109 | + try { |
| 110 | + return $decrypt($fallback_private_key_path); |
| 111 | + } catch (\InvalidArgumentException $fallback_exception) { |
| 112 | + throw new \InvalidArgumentException(sprintf( |
| 113 | + "Decryption failed: [%s]\nFallback also failed: [%s]", |
| 114 | + $e->getMessage(), |
| 115 | + $fallback_exception->getMessage() |
| 116 | + ), 0, $e); |
| 117 | + } |
| 118 | + } |
99 | 119 | {% elseif property.type == 'integer' %} |
100 | 120 | return (int) $this->{{ property.name }}; |
101 | 121 | {% elseif property.collection %} |
|
0 commit comments