RSA.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. public function __construct(
  20. IL10N $l,
  21. private IConfig $config,
  22. ) {
  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. }