OpenSSH.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * OpenSSH Formatted RSA Key Handler
  4. *
  5. * PHP version 5
  6. *
  7. * Place in $HOME/.ssh/authorized_keys
  8. *
  9. * @category Crypt
  10. * @package RSA
  11. * @author Jim Wigginton <terrafrost@php.net>
  12. * @copyright 2015 Jim Wigginton
  13. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  14. * @link http://phpseclib.sourceforge.net
  15. */
  16. namespace phpseclib\Crypt\RSA\Keys;
  17. use ParagonIE\ConstantTime\Base64;
  18. use phpseclib\Math\BigInteger;
  19. use phpseclib\Common\Functions\Strings;
  20. use phpseclib\Crypt\Common\Keys\OpenSSH as Progenitor;
  21. /**
  22. * OpenSSH Formatted RSA Key Handler
  23. *
  24. * @package RSA
  25. * @author Jim Wigginton <terrafrost@php.net>
  26. * @access public
  27. */
  28. abstract class OpenSSH extends Progenitor
  29. {
  30. /**
  31. * Break a public or private key down into its constituent components
  32. *
  33. * @access public
  34. * @param string $key
  35. * @param string $password optional
  36. * @return array
  37. */
  38. public static function load($key, $password = '')
  39. {
  40. $key = parent::load($key, 'ssh-rsa');
  41. if ($key === false) {
  42. return false;
  43. }
  44. $result = Strings::unpackSSH2('ii', $key);
  45. if ($result === false) {
  46. return false;
  47. }
  48. list($publicExponent, $modulus) = $result;
  49. return [
  50. 'isPublicKey' => true,
  51. 'modulus' => $modulus,
  52. 'publicExponent' => $publicExponent,
  53. 'comment' => parent::getComment($key)
  54. ];
  55. }
  56. /**
  57. * Convert a public key to the appropriate format
  58. *
  59. * @access public
  60. * @param \phpseclib\Math\BigInteger $n
  61. * @param \phpseclib\Math\BigInteger $e
  62. * @return string
  63. */
  64. public static function savePublicKey($n, $e)
  65. {
  66. $RSAPublicKey = Strings::packSSH2('sii', 'ssh-rsa', $e, $n);
  67. if (self::$binary) {
  68. return $RSAPublicKey;
  69. }
  70. $RSAPublicKey = 'ssh-rsa ' . Base64::encode($RSAPublicKey) . ' ' . self::$comment;
  71. return $RSAPublicKey;
  72. }
  73. }