RSA.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_External\Lib\Auth\PublicKey;
  8. use OCA\Files_External\Lib\Auth\AuthMechanism;
  9. use OCA\Files_External\Lib\DefinitionParameter;
  10. use OCA\Files_External\Lib\StorageConfig;
  11. use OCP\IConfig;
  12. use OCP\IL10N;
  13. use OCP\IUser;
  14. use phpseclib\Crypt\RSA as RSACrypt;
  15. /**
  16. * RSA public key authentication
  17. */
  18. class RSA extends AuthMechanism {
  19. /** @var IConfig */
  20. private $config;
  21. public function __construct(IL10N $l, IConfig $config) {
  22. $this->config = $config;
  23. $this
  24. ->setIdentifier('publickey::rsa')
  25. ->setScheme(self::SCHEME_PUBLICKEY)
  26. ->setText($l->t('RSA public key'))
  27. ->addParameters([
  28. new DefinitionParameter('user', $l->t('Login')),
  29. new DefinitionParameter('public_key', $l->t('Public key')),
  30. (new DefinitionParameter('private_key', 'private_key'))
  31. ->setType(DefinitionParameter::VALUE_HIDDEN),
  32. ])
  33. ->addCustomJs('public_key')
  34. ;
  35. }
  36. /**
  37. * @return void
  38. */
  39. public function manipulateStorageConfig(StorageConfig &$storage, ?IUser $user = null) {
  40. $auth = new RSACrypt();
  41. $auth->setPassword($this->config->getSystemValue('secret', ''));
  42. if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
  43. // Add fallback routine for a time where secret was not enforced to be exists
  44. $auth->setPassword('');
  45. if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
  46. throw new \RuntimeException('unable to load private key');
  47. }
  48. }
  49. $storage->setBackendOption('public_key_auth', $auth);
  50. }
  51. /**
  52. * Generate a keypair
  53. *
  54. * @param int $keyLenth
  55. * @return array ['privatekey' => $privateKey, 'publickey' => $publicKey]
  56. */
  57. public function createKey($keyLength) {
  58. $rsa = new RSACrypt();
  59. $rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH);
  60. $rsa->setPassword($this->config->getSystemValue('secret', ''));
  61. if ($keyLength !== 1024 && $keyLength !== 2048 && $keyLength !== 4096) {
  62. $keyLength = 1024;
  63. }
  64. return $rsa->createKey($keyLength);
  65. }
  66. }