OpenSSH.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * OpenSSH Formatted DSA Key Handler
  4. *
  5. * PHP version 5
  6. *
  7. * Place in $HOME/.ssh/authorized_keys
  8. *
  9. * @category Crypt
  10. * @package DSA
  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\DSA\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 DSA Key Handler
  23. *
  24. * @package DSA
  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-dss');
  41. if ($key === false) {
  42. return false;
  43. }
  44. $result = Strings::unpackSSH2('iiii', $key);
  45. if ($result === false) {
  46. return false;
  47. }
  48. list($p, $q, $g, $y) = $result;
  49. $comment = parent::getComment($key);
  50. return compact('p', 'q', 'g', 'y', 'comment');
  51. }
  52. /**
  53. * Convert a public key to the appropriate format
  54. *
  55. * @access public
  56. * @param \phpseclib\Math\BigInteger $p
  57. * @param \phpseclib\Math\BigInteger $q
  58. * @param \phpseclib\Math\BigInteger $g
  59. * @param \phpseclib\Math\BigInteger $y
  60. * @return string
  61. */
  62. public static function savePublicKey($p, $q, $g, $y)
  63. {
  64. if ($q->getLength() != 160) {
  65. throw new \InvalidArgumentException('SSH only supports keys with an N (length of Group Order q) of 160');
  66. }
  67. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  68. // string "ssh-dss"
  69. // mpint p
  70. // mpint q
  71. // mpint g
  72. // mpint y
  73. $DSAPublicKey = Strings::packSSH2('siiii', 'ssh-dss', $p, $q, $g, $y);
  74. if (self::$binary) {
  75. return $DSAPublicKey;
  76. }
  77. $DSAPublicKey = 'ssh-dss ' . Base64::encode($DSAPublicKey) . ' ' . self::$comment;
  78. return $DSAPublicKey;
  79. }
  80. }