You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

keys.go 34 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ssh
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/dsa"
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/md5"
  12. "crypto/rsa"
  13. "crypto/sha256"
  14. "crypto/x509"
  15. "encoding/asn1"
  16. "encoding/base64"
  17. "encoding/hex"
  18. "encoding/pem"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "strings"
  24. "golang.org/x/crypto/ed25519"
  25. )
  26. // These constants represent the algorithm names for key types supported by this
  27. // package.
  28. const (
  29. KeyAlgoRSA = "ssh-rsa"
  30. KeyAlgoDSA = "ssh-dss"
  31. KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
  32. KeyAlgoSKECDSA256 = "sk-ecdsa-sha2-nistp256@openssh.com"
  33. KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
  34. KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
  35. KeyAlgoED25519 = "ssh-ed25519"
  36. KeyAlgoSKED25519 = "sk-ssh-ed25519@openssh.com"
  37. )
  38. // These constants represent non-default signature algorithms that are supported
  39. // as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See
  40. // [PROTOCOL.agent] section 4.5.1 and
  41. // https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10
  42. const (
  43. SigAlgoRSA = "ssh-rsa"
  44. SigAlgoRSASHA2256 = "rsa-sha2-256"
  45. SigAlgoRSASHA2512 = "rsa-sha2-512"
  46. )
  47. // parsePubKey parses a public key of the given algorithm.
  48. // Use ParsePublicKey for keys with prepended algorithm.
  49. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) {
  50. switch algo {
  51. case KeyAlgoRSA:
  52. return parseRSA(in)
  53. case KeyAlgoDSA:
  54. return parseDSA(in)
  55. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  56. return parseECDSA(in)
  57. case KeyAlgoSKECDSA256:
  58. return parseSKECDSA(in)
  59. case KeyAlgoED25519:
  60. return parseED25519(in)
  61. case KeyAlgoSKED25519:
  62. return parseSKEd25519(in)
  63. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, CertAlgoSKED25519v01:
  64. cert, err := parseCert(in, certToPrivAlgo(algo))
  65. if err != nil {
  66. return nil, nil, err
  67. }
  68. return cert, nil, nil
  69. }
  70. return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo)
  71. }
  72. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  73. // (see sshd(8) manual page) once the options and key type fields have been
  74. // removed.
  75. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) {
  76. in = bytes.TrimSpace(in)
  77. i := bytes.IndexAny(in, " \t")
  78. if i == -1 {
  79. i = len(in)
  80. }
  81. base64Key := in[:i]
  82. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  83. n, err := base64.StdEncoding.Decode(key, base64Key)
  84. if err != nil {
  85. return nil, "", err
  86. }
  87. key = key[:n]
  88. out, err = ParsePublicKey(key)
  89. if err != nil {
  90. return nil, "", err
  91. }
  92. comment = string(bytes.TrimSpace(in[i:]))
  93. return out, comment, nil
  94. }
  95. // ParseKnownHosts parses an entry in the format of the known_hosts file.
  96. //
  97. // The known_hosts format is documented in the sshd(8) manual page. This
  98. // function will parse a single entry from in. On successful return, marker
  99. // will contain the optional marker value (i.e. "cert-authority" or "revoked")
  100. // or else be empty, hosts will contain the hosts that this entry matches,
  101. // pubKey will contain the public key and comment will contain any trailing
  102. // comment at the end of the line. See the sshd(8) manual page for the various
  103. // forms that a host string can take.
  104. //
  105. // The unparsed remainder of the input will be returned in rest. This function
  106. // can be called repeatedly to parse multiple entries.
  107. //
  108. // If no entries were found in the input then err will be io.EOF. Otherwise a
  109. // non-nil err value indicates a parse error.
  110. func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) {
  111. for len(in) > 0 {
  112. end := bytes.IndexByte(in, '\n')
  113. if end != -1 {
  114. rest = in[end+1:]
  115. in = in[:end]
  116. } else {
  117. rest = nil
  118. }
  119. end = bytes.IndexByte(in, '\r')
  120. if end != -1 {
  121. in = in[:end]
  122. }
  123. in = bytes.TrimSpace(in)
  124. if len(in) == 0 || in[0] == '#' {
  125. in = rest
  126. continue
  127. }
  128. i := bytes.IndexAny(in, " \t")
  129. if i == -1 {
  130. in = rest
  131. continue
  132. }
  133. // Strip out the beginning of the known_host key.
  134. // This is either an optional marker or a (set of) hostname(s).
  135. keyFields := bytes.Fields(in)
  136. if len(keyFields) < 3 || len(keyFields) > 5 {
  137. return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data")
  138. }
  139. // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated
  140. // list of hosts
  141. marker := ""
  142. if keyFields[0][0] == '@' {
  143. marker = string(keyFields[0][1:])
  144. keyFields = keyFields[1:]
  145. }
  146. hosts := string(keyFields[0])
  147. // keyFields[1] contains the key type (e.g. “ssh-rsa”).
  148. // However, that information is duplicated inside the
  149. // base64-encoded key and so is ignored here.
  150. key := bytes.Join(keyFields[2:], []byte(" "))
  151. if pubKey, comment, err = parseAuthorizedKey(key); err != nil {
  152. return "", nil, nil, "", nil, err
  153. }
  154. return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil
  155. }
  156. return "", nil, nil, "", nil, io.EOF
  157. }
  158. // ParseAuthorizedKeys parses a public key from an authorized_keys
  159. // file used in OpenSSH according to the sshd(8) manual page.
  160. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) {
  161. for len(in) > 0 {
  162. end := bytes.IndexByte(in, '\n')
  163. if end != -1 {
  164. rest = in[end+1:]
  165. in = in[:end]
  166. } else {
  167. rest = nil
  168. }
  169. end = bytes.IndexByte(in, '\r')
  170. if end != -1 {
  171. in = in[:end]
  172. }
  173. in = bytes.TrimSpace(in)
  174. if len(in) == 0 || in[0] == '#' {
  175. in = rest
  176. continue
  177. }
  178. i := bytes.IndexAny(in, " \t")
  179. if i == -1 {
  180. in = rest
  181. continue
  182. }
  183. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  184. return out, comment, options, rest, nil
  185. }
  186. // No key type recognised. Maybe there's an options field at
  187. // the beginning.
  188. var b byte
  189. inQuote := false
  190. var candidateOptions []string
  191. optionStart := 0
  192. for i, b = range in {
  193. isEnd := !inQuote && (b == ' ' || b == '\t')
  194. if (b == ',' && !inQuote) || isEnd {
  195. if i-optionStart > 0 {
  196. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  197. }
  198. optionStart = i + 1
  199. }
  200. if isEnd {
  201. break
  202. }
  203. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  204. inQuote = !inQuote
  205. }
  206. }
  207. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  208. i++
  209. }
  210. if i == len(in) {
  211. // Invalid line: unmatched quote
  212. in = rest
  213. continue
  214. }
  215. in = in[i:]
  216. i = bytes.IndexAny(in, " \t")
  217. if i == -1 {
  218. in = rest
  219. continue
  220. }
  221. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  222. options = candidateOptions
  223. return out, comment, options, rest, nil
  224. }
  225. in = rest
  226. continue
  227. }
  228. return nil, "", nil, nil, errors.New("ssh: no key found")
  229. }
  230. // ParsePublicKey parses an SSH public key formatted for use in
  231. // the SSH wire protocol according to RFC 4253, section 6.6.
  232. func ParsePublicKey(in []byte) (out PublicKey, err error) {
  233. algo, in, ok := parseString(in)
  234. if !ok {
  235. return nil, errShortRead
  236. }
  237. var rest []byte
  238. out, rest, err = parsePubKey(in, string(algo))
  239. if len(rest) > 0 {
  240. return nil, errors.New("ssh: trailing junk in public key")
  241. }
  242. return out, err
  243. }
  244. // MarshalAuthorizedKey serializes key for inclusion in an OpenSSH
  245. // authorized_keys file. The return value ends with newline.
  246. func MarshalAuthorizedKey(key PublicKey) []byte {
  247. b := &bytes.Buffer{}
  248. b.WriteString(key.Type())
  249. b.WriteByte(' ')
  250. e := base64.NewEncoder(base64.StdEncoding, b)
  251. e.Write(key.Marshal())
  252. e.Close()
  253. b.WriteByte('\n')
  254. return b.Bytes()
  255. }
  256. // PublicKey is an abstraction of different types of public keys.
  257. type PublicKey interface {
  258. // Type returns the key's type, e.g. "ssh-rsa".
  259. Type() string
  260. // Marshal returns the serialized key data in SSH wire format,
  261. // with the name prefix. To unmarshal the returned data, use
  262. // the ParsePublicKey function.
  263. Marshal() []byte
  264. // Verify that sig is a signature on the given data using this
  265. // key. This function will hash the data appropriately first.
  266. Verify(data []byte, sig *Signature) error
  267. }
  268. // CryptoPublicKey, if implemented by a PublicKey,
  269. // returns the underlying crypto.PublicKey form of the key.
  270. type CryptoPublicKey interface {
  271. CryptoPublicKey() crypto.PublicKey
  272. }
  273. // A Signer can create signatures that verify against a public key.
  274. type Signer interface {
  275. // PublicKey returns an associated PublicKey instance.
  276. PublicKey() PublicKey
  277. // Sign returns raw signature for the given data. This method
  278. // will apply the hash specified for the keytype to the data.
  279. Sign(rand io.Reader, data []byte) (*Signature, error)
  280. }
  281. // A AlgorithmSigner is a Signer that also supports specifying a specific
  282. // algorithm to use for signing.
  283. type AlgorithmSigner interface {
  284. Signer
  285. // SignWithAlgorithm is like Signer.Sign, but allows specification of a
  286. // non-default signing algorithm. See the SigAlgo* constants in this
  287. // package for signature algorithms supported by this package. Callers may
  288. // pass an empty string for the algorithm in which case the AlgorithmSigner
  289. // will use its default algorithm.
  290. SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error)
  291. }
  292. type rsaPublicKey rsa.PublicKey
  293. func (r *rsaPublicKey) Type() string {
  294. return "ssh-rsa"
  295. }
  296. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  297. func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
  298. var w struct {
  299. E *big.Int
  300. N *big.Int
  301. Rest []byte `ssh:"rest"`
  302. }
  303. if err := Unmarshal(in, &w); err != nil {
  304. return nil, nil, err
  305. }
  306. if w.E.BitLen() > 24 {
  307. return nil, nil, errors.New("ssh: exponent too large")
  308. }
  309. e := w.E.Int64()
  310. if e < 3 || e&1 == 0 {
  311. return nil, nil, errors.New("ssh: incorrect exponent")
  312. }
  313. var key rsa.PublicKey
  314. key.E = int(e)
  315. key.N = w.N
  316. return (*rsaPublicKey)(&key), w.Rest, nil
  317. }
  318. func (r *rsaPublicKey) Marshal() []byte {
  319. e := new(big.Int).SetInt64(int64(r.E))
  320. // RSA publickey struct layout should match the struct used by
  321. // parseRSACert in the x/crypto/ssh/agent package.
  322. wirekey := struct {
  323. Name string
  324. E *big.Int
  325. N *big.Int
  326. }{
  327. KeyAlgoRSA,
  328. e,
  329. r.N,
  330. }
  331. return Marshal(&wirekey)
  332. }
  333. func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
  334. var hash crypto.Hash
  335. switch sig.Format {
  336. case SigAlgoRSA:
  337. hash = crypto.SHA1
  338. case SigAlgoRSASHA2256:
  339. hash = crypto.SHA256
  340. case SigAlgoRSASHA2512:
  341. hash = crypto.SHA512
  342. default:
  343. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
  344. }
  345. h := hash.New()
  346. h.Write(data)
  347. digest := h.Sum(nil)
  348. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), hash, digest, sig.Blob)
  349. }
  350. func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  351. return (*rsa.PublicKey)(r)
  352. }
  353. type dsaPublicKey dsa.PublicKey
  354. func (k *dsaPublicKey) Type() string {
  355. return "ssh-dss"
  356. }
  357. func checkDSAParams(param *dsa.Parameters) error {
  358. // SSH specifies FIPS 186-2, which only provided a single size
  359. // (1024 bits) DSA key. FIPS 186-3 allows for larger key
  360. // sizes, which would confuse SSH.
  361. if l := param.P.BitLen(); l != 1024 {
  362. return fmt.Errorf("ssh: unsupported DSA key size %d", l)
  363. }
  364. return nil
  365. }
  366. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  367. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  368. var w struct {
  369. P, Q, G, Y *big.Int
  370. Rest []byte `ssh:"rest"`
  371. }
  372. if err := Unmarshal(in, &w); err != nil {
  373. return nil, nil, err
  374. }
  375. param := dsa.Parameters{
  376. P: w.P,
  377. Q: w.Q,
  378. G: w.G,
  379. }
  380. if err := checkDSAParams(&param); err != nil {
  381. return nil, nil, err
  382. }
  383. key := &dsaPublicKey{
  384. Parameters: param,
  385. Y: w.Y,
  386. }
  387. return key, w.Rest, nil
  388. }
  389. func (k *dsaPublicKey) Marshal() []byte {
  390. // DSA publickey struct layout should match the struct used by
  391. // parseDSACert in the x/crypto/ssh/agent package.
  392. w := struct {
  393. Name string
  394. P, Q, G, Y *big.Int
  395. }{
  396. k.Type(),
  397. k.P,
  398. k.Q,
  399. k.G,
  400. k.Y,
  401. }
  402. return Marshal(&w)
  403. }
  404. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  405. if sig.Format != k.Type() {
  406. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  407. }
  408. h := crypto.SHA1.New()
  409. h.Write(data)
  410. digest := h.Sum(nil)
  411. // Per RFC 4253, section 6.6,
  412. // The value for 'dss_signature_blob' is encoded as a string containing
  413. // r, followed by s (which are 160-bit integers, without lengths or
  414. // padding, unsigned, and in network byte order).
  415. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  416. if len(sig.Blob) != 40 {
  417. return errors.New("ssh: DSA signature parse error")
  418. }
  419. r := new(big.Int).SetBytes(sig.Blob[:20])
  420. s := new(big.Int).SetBytes(sig.Blob[20:])
  421. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  422. return nil
  423. }
  424. return errors.New("ssh: signature did not verify")
  425. }
  426. func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  427. return (*dsa.PublicKey)(k)
  428. }
  429. type dsaPrivateKey struct {
  430. *dsa.PrivateKey
  431. }
  432. func (k *dsaPrivateKey) PublicKey() PublicKey {
  433. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  434. }
  435. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  436. return k.SignWithAlgorithm(rand, data, "")
  437. }
  438. func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  439. if algorithm != "" && algorithm != k.PublicKey().Type() {
  440. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  441. }
  442. h := crypto.SHA1.New()
  443. h.Write(data)
  444. digest := h.Sum(nil)
  445. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  446. if err != nil {
  447. return nil, err
  448. }
  449. sig := make([]byte, 40)
  450. rb := r.Bytes()
  451. sb := s.Bytes()
  452. copy(sig[20-len(rb):20], rb)
  453. copy(sig[40-len(sb):], sb)
  454. return &Signature{
  455. Format: k.PublicKey().Type(),
  456. Blob: sig,
  457. }, nil
  458. }
  459. type ecdsaPublicKey ecdsa.PublicKey
  460. func (k *ecdsaPublicKey) Type() string {
  461. return "ecdsa-sha2-" + k.nistID()
  462. }
  463. func (k *ecdsaPublicKey) nistID() string {
  464. switch k.Params().BitSize {
  465. case 256:
  466. return "nistp256"
  467. case 384:
  468. return "nistp384"
  469. case 521:
  470. return "nistp521"
  471. }
  472. panic("ssh: unsupported ecdsa key size")
  473. }
  474. type ed25519PublicKey ed25519.PublicKey
  475. func (k ed25519PublicKey) Type() string {
  476. return KeyAlgoED25519
  477. }
  478. func parseED25519(in []byte) (out PublicKey, rest []byte, err error) {
  479. var w struct {
  480. KeyBytes []byte
  481. Rest []byte `ssh:"rest"`
  482. }
  483. if err := Unmarshal(in, &w); err != nil {
  484. return nil, nil, err
  485. }
  486. key := ed25519.PublicKey(w.KeyBytes)
  487. return (ed25519PublicKey)(key), w.Rest, nil
  488. }
  489. func (k ed25519PublicKey) Marshal() []byte {
  490. w := struct {
  491. Name string
  492. KeyBytes []byte
  493. }{
  494. KeyAlgoED25519,
  495. []byte(k),
  496. }
  497. return Marshal(&w)
  498. }
  499. func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error {
  500. if sig.Format != k.Type() {
  501. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  502. }
  503. edKey := (ed25519.PublicKey)(k)
  504. if ok := ed25519.Verify(edKey, b, sig.Blob); !ok {
  505. return errors.New("ssh: signature did not verify")
  506. }
  507. return nil
  508. }
  509. func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  510. return ed25519.PublicKey(k)
  511. }
  512. func supportedEllipticCurve(curve elliptic.Curve) bool {
  513. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  514. }
  515. // ecHash returns the hash to match the given elliptic curve, see RFC
  516. // 5656, section 6.2.1
  517. func ecHash(curve elliptic.Curve) crypto.Hash {
  518. bitSize := curve.Params().BitSize
  519. switch {
  520. case bitSize <= 256:
  521. return crypto.SHA256
  522. case bitSize <= 384:
  523. return crypto.SHA384
  524. }
  525. return crypto.SHA512
  526. }
  527. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  528. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  529. var w struct {
  530. Curve string
  531. KeyBytes []byte
  532. Rest []byte `ssh:"rest"`
  533. }
  534. if err := Unmarshal(in, &w); err != nil {
  535. return nil, nil, err
  536. }
  537. key := new(ecdsa.PublicKey)
  538. switch w.Curve {
  539. case "nistp256":
  540. key.Curve = elliptic.P256()
  541. case "nistp384":
  542. key.Curve = elliptic.P384()
  543. case "nistp521":
  544. key.Curve = elliptic.P521()
  545. default:
  546. return nil, nil, errors.New("ssh: unsupported curve")
  547. }
  548. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  549. if key.X == nil || key.Y == nil {
  550. return nil, nil, errors.New("ssh: invalid curve point")
  551. }
  552. return (*ecdsaPublicKey)(key), w.Rest, nil
  553. }
  554. func (k *ecdsaPublicKey) Marshal() []byte {
  555. // See RFC 5656, section 3.1.
  556. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  557. // ECDSA publickey struct layout should match the struct used by
  558. // parseECDSACert in the x/crypto/ssh/agent package.
  559. w := struct {
  560. Name string
  561. ID string
  562. Key []byte
  563. }{
  564. k.Type(),
  565. k.nistID(),
  566. keyBytes,
  567. }
  568. return Marshal(&w)
  569. }
  570. func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  571. if sig.Format != k.Type() {
  572. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  573. }
  574. h := ecHash(k.Curve).New()
  575. h.Write(data)
  576. digest := h.Sum(nil)
  577. // Per RFC 5656, section 3.1.2,
  578. // The ecdsa_signature_blob value has the following specific encoding:
  579. // mpint r
  580. // mpint s
  581. var ecSig struct {
  582. R *big.Int
  583. S *big.Int
  584. }
  585. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  586. return err
  587. }
  588. if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) {
  589. return nil
  590. }
  591. return errors.New("ssh: signature did not verify")
  592. }
  593. func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  594. return (*ecdsa.PublicKey)(k)
  595. }
  596. // skFields holds the additional fields present in U2F/FIDO2 signatures.
  597. // See openssh/PROTOCOL.u2f 'SSH U2F Signatures' for details.
  598. type skFields struct {
  599. // Flags contains U2F/FIDO2 flags such as 'user present'
  600. Flags byte
  601. // Counter is a monotonic signature counter which can be
  602. // used to detect concurrent use of a private key, should
  603. // it be extracted from hardware.
  604. Counter uint32
  605. }
  606. type skECDSAPublicKey struct {
  607. // application is a URL-like string, typically "ssh:" for SSH.
  608. // see openssh/PROTOCOL.u2f for details.
  609. application string
  610. ecdsa.PublicKey
  611. }
  612. func (k *skECDSAPublicKey) Type() string {
  613. return KeyAlgoSKECDSA256
  614. }
  615. func (k *skECDSAPublicKey) nistID() string {
  616. return "nistp256"
  617. }
  618. func parseSKECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  619. var w struct {
  620. Curve string
  621. KeyBytes []byte
  622. Application string
  623. Rest []byte `ssh:"rest"`
  624. }
  625. if err := Unmarshal(in, &w); err != nil {
  626. return nil, nil, err
  627. }
  628. key := new(skECDSAPublicKey)
  629. key.application = w.Application
  630. if w.Curve != "nistp256" {
  631. return nil, nil, errors.New("ssh: unsupported curve")
  632. }
  633. key.Curve = elliptic.P256()
  634. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  635. if key.X == nil || key.Y == nil {
  636. return nil, nil, errors.New("ssh: invalid curve point")
  637. }
  638. return key, w.Rest, nil
  639. }
  640. func (k *skECDSAPublicKey) Marshal() []byte {
  641. // See RFC 5656, section 3.1.
  642. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  643. w := struct {
  644. Name string
  645. ID string
  646. Key []byte
  647. Application string
  648. }{
  649. k.Type(),
  650. k.nistID(),
  651. keyBytes,
  652. k.application,
  653. }
  654. return Marshal(&w)
  655. }
  656. func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
  657. if sig.Format != k.Type() {
  658. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  659. }
  660. h := ecHash(k.Curve).New()
  661. h.Write([]byte(k.application))
  662. appDigest := h.Sum(nil)
  663. h.Reset()
  664. h.Write(data)
  665. dataDigest := h.Sum(nil)
  666. var ecSig struct {
  667. R *big.Int
  668. S *big.Int
  669. }
  670. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  671. return err
  672. }
  673. var skf skFields
  674. if err := Unmarshal(sig.Rest, &skf); err != nil {
  675. return err
  676. }
  677. blob := struct {
  678. ApplicationDigest []byte `ssh:"rest"`
  679. Flags byte
  680. Counter uint32
  681. MessageDigest []byte `ssh:"rest"`
  682. }{
  683. appDigest,
  684. skf.Flags,
  685. skf.Counter,
  686. dataDigest,
  687. }
  688. original := Marshal(blob)
  689. h.Reset()
  690. h.Write(original)
  691. digest := h.Sum(nil)
  692. if ecdsa.Verify((*ecdsa.PublicKey)(&k.PublicKey), digest, ecSig.R, ecSig.S) {
  693. return nil
  694. }
  695. return errors.New("ssh: signature did not verify")
  696. }
  697. type skEd25519PublicKey struct {
  698. // application is a URL-like string, typically "ssh:" for SSH.
  699. // see openssh/PROTOCOL.u2f for details.
  700. application string
  701. ed25519.PublicKey
  702. }
  703. func (k *skEd25519PublicKey) Type() string {
  704. return KeyAlgoSKED25519
  705. }
  706. func parseSKEd25519(in []byte) (out PublicKey, rest []byte, err error) {
  707. var w struct {
  708. KeyBytes []byte
  709. Application string
  710. Rest []byte `ssh:"rest"`
  711. }
  712. if err := Unmarshal(in, &w); err != nil {
  713. return nil, nil, err
  714. }
  715. key := new(skEd25519PublicKey)
  716. key.application = w.Application
  717. key.PublicKey = ed25519.PublicKey(w.KeyBytes)
  718. return key, w.Rest, nil
  719. }
  720. func (k *skEd25519PublicKey) Marshal() []byte {
  721. w := struct {
  722. Name string
  723. KeyBytes []byte
  724. Application string
  725. }{
  726. KeyAlgoSKED25519,
  727. []byte(k.PublicKey),
  728. k.application,
  729. }
  730. return Marshal(&w)
  731. }
  732. func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
  733. if sig.Format != k.Type() {
  734. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  735. }
  736. h := sha256.New()
  737. h.Write([]byte(k.application))
  738. appDigest := h.Sum(nil)
  739. h.Reset()
  740. h.Write(data)
  741. dataDigest := h.Sum(nil)
  742. var edSig struct {
  743. Signature []byte `ssh:"rest"`
  744. }
  745. if err := Unmarshal(sig.Blob, &edSig); err != nil {
  746. return err
  747. }
  748. var skf skFields
  749. if err := Unmarshal(sig.Rest, &skf); err != nil {
  750. return err
  751. }
  752. blob := struct {
  753. ApplicationDigest []byte `ssh:"rest"`
  754. Flags byte
  755. Counter uint32
  756. MessageDigest []byte `ssh:"rest"`
  757. }{
  758. appDigest,
  759. skf.Flags,
  760. skf.Counter,
  761. dataDigest,
  762. }
  763. original := Marshal(blob)
  764. edKey := (ed25519.PublicKey)(k.PublicKey)
  765. if ok := ed25519.Verify(edKey, original, edSig.Signature); !ok {
  766. return errors.New("ssh: signature did not verify")
  767. }
  768. return nil
  769. }
  770. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  771. // *ecdsa.PrivateKey or any other crypto.Signer and returns a
  772. // corresponding Signer instance. ECDSA keys must use P-256, P-384 or
  773. // P-521. DSA keys must use parameter size L1024N160.
  774. func NewSignerFromKey(key interface{}) (Signer, error) {
  775. switch key := key.(type) {
  776. case crypto.Signer:
  777. return NewSignerFromSigner(key)
  778. case *dsa.PrivateKey:
  779. return newDSAPrivateKey(key)
  780. default:
  781. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  782. }
  783. }
  784. func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) {
  785. if err := checkDSAParams(&key.PublicKey.Parameters); err != nil {
  786. return nil, err
  787. }
  788. return &dsaPrivateKey{key}, nil
  789. }
  790. type wrappedSigner struct {
  791. signer crypto.Signer
  792. pubKey PublicKey
  793. }
  794. // NewSignerFromSigner takes any crypto.Signer implementation and
  795. // returns a corresponding Signer interface. This can be used, for
  796. // example, with keys kept in hardware modules.
  797. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  798. pubKey, err := NewPublicKey(signer.Public())
  799. if err != nil {
  800. return nil, err
  801. }
  802. return &wrappedSigner{signer, pubKey}, nil
  803. }
  804. func (s *wrappedSigner) PublicKey() PublicKey {
  805. return s.pubKey
  806. }
  807. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  808. return s.SignWithAlgorithm(rand, data, "")
  809. }
  810. func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  811. var hashFunc crypto.Hash
  812. if _, ok := s.pubKey.(*rsaPublicKey); ok {
  813. // RSA keys support a few hash functions determined by the requested signature algorithm
  814. switch algorithm {
  815. case "", SigAlgoRSA:
  816. algorithm = SigAlgoRSA
  817. hashFunc = crypto.SHA1
  818. case SigAlgoRSASHA2256:
  819. hashFunc = crypto.SHA256
  820. case SigAlgoRSASHA2512:
  821. hashFunc = crypto.SHA512
  822. default:
  823. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  824. }
  825. } else {
  826. // The only supported algorithm for all other key types is the same as the type of the key
  827. if algorithm == "" {
  828. algorithm = s.pubKey.Type()
  829. } else if algorithm != s.pubKey.Type() {
  830. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  831. }
  832. switch key := s.pubKey.(type) {
  833. case *dsaPublicKey:
  834. hashFunc = crypto.SHA1
  835. case *ecdsaPublicKey:
  836. hashFunc = ecHash(key.Curve)
  837. case ed25519PublicKey:
  838. default:
  839. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  840. }
  841. }
  842. var digest []byte
  843. if hashFunc != 0 {
  844. h := hashFunc.New()
  845. h.Write(data)
  846. digest = h.Sum(nil)
  847. } else {
  848. digest = data
  849. }
  850. signature, err := s.signer.Sign(rand, digest, hashFunc)
  851. if err != nil {
  852. return nil, err
  853. }
  854. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  855. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  856. // re-encode.
  857. switch s.pubKey.(type) {
  858. case *ecdsaPublicKey, *dsaPublicKey:
  859. type asn1Signature struct {
  860. R, S *big.Int
  861. }
  862. asn1Sig := new(asn1Signature)
  863. _, err := asn1.Unmarshal(signature, asn1Sig)
  864. if err != nil {
  865. return nil, err
  866. }
  867. switch s.pubKey.(type) {
  868. case *ecdsaPublicKey:
  869. signature = Marshal(asn1Sig)
  870. case *dsaPublicKey:
  871. signature = make([]byte, 40)
  872. r := asn1Sig.R.Bytes()
  873. s := asn1Sig.S.Bytes()
  874. copy(signature[20-len(r):20], r)
  875. copy(signature[40-len(s):40], s)
  876. }
  877. }
  878. return &Signature{
  879. Format: algorithm,
  880. Blob: signature,
  881. }, nil
  882. }
  883. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  884. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  885. // ECDSA keys must use P-256, P-384 or P-521.
  886. func NewPublicKey(key interface{}) (PublicKey, error) {
  887. switch key := key.(type) {
  888. case *rsa.PublicKey:
  889. return (*rsaPublicKey)(key), nil
  890. case *ecdsa.PublicKey:
  891. if !supportedEllipticCurve(key.Curve) {
  892. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported")
  893. }
  894. return (*ecdsaPublicKey)(key), nil
  895. case *dsa.PublicKey:
  896. return (*dsaPublicKey)(key), nil
  897. case ed25519.PublicKey:
  898. return (ed25519PublicKey)(key), nil
  899. default:
  900. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  901. }
  902. }
  903. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  904. // the same keys as ParseRawPrivateKey. If the private key is encrypted, it
  905. // will return a PassphraseMissingError.
  906. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  907. key, err := ParseRawPrivateKey(pemBytes)
  908. if err != nil {
  909. return nil, err
  910. }
  911. return NewSignerFromKey(key)
  912. }
  913. // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
  914. // key and passphrase. It supports the same keys as
  915. // ParseRawPrivateKeyWithPassphrase.
  916. func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) {
  917. key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)
  918. if err != nil {
  919. return nil, err
  920. }
  921. return NewSignerFromKey(key)
  922. }
  923. // encryptedBlock tells whether a private key is
  924. // encrypted by examining its Proc-Type header
  925. // for a mention of ENCRYPTED
  926. // according to RFC 1421 Section 4.6.1.1.
  927. func encryptedBlock(block *pem.Block) bool {
  928. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  929. }
  930. // A PassphraseMissingError indicates that parsing this private key requires a
  931. // passphrase. Use ParsePrivateKeyWithPassphrase.
  932. type PassphraseMissingError struct {
  933. // PublicKey will be set if the private key format includes an unencrypted
  934. // public key along with the encrypted private key.
  935. PublicKey PublicKey
  936. }
  937. func (*PassphraseMissingError) Error() string {
  938. return "ssh: this private key is passphrase protected"
  939. }
  940. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  941. // supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. If the
  942. // private key is encrypted, it will return a PassphraseMissingError.
  943. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  944. block, _ := pem.Decode(pemBytes)
  945. if block == nil {
  946. return nil, errors.New("ssh: no key found")
  947. }
  948. if encryptedBlock(block) {
  949. return nil, &PassphraseMissingError{}
  950. }
  951. switch block.Type {
  952. case "RSA PRIVATE KEY":
  953. return x509.ParsePKCS1PrivateKey(block.Bytes)
  954. // RFC5208 - https://tools.ietf.org/html/rfc5208
  955. case "PRIVATE KEY":
  956. return x509.ParsePKCS8PrivateKey(block.Bytes)
  957. case "EC PRIVATE KEY":
  958. return x509.ParseECPrivateKey(block.Bytes)
  959. case "DSA PRIVATE KEY":
  960. return ParseDSAPrivateKey(block.Bytes)
  961. case "OPENSSH PRIVATE KEY":
  962. return parseOpenSSHPrivateKey(block.Bytes)
  963. default:
  964. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  965. }
  966. }
  967. // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
  968. // passphrase from a PEM encoded private key. If wrong passphrase, return
  969. // x509.IncorrectPasswordError.
  970. func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
  971. block, _ := pem.Decode(pemBytes)
  972. if block == nil {
  973. return nil, errors.New("ssh: no key found")
  974. }
  975. if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
  976. return nil, errors.New("ssh: not an encrypted key")
  977. }
  978. buf, err := x509.DecryptPEMBlock(block, passphrase)
  979. if err != nil {
  980. if err == x509.IncorrectPasswordError {
  981. return nil, err
  982. }
  983. return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
  984. }
  985. switch block.Type {
  986. case "RSA PRIVATE KEY":
  987. return x509.ParsePKCS1PrivateKey(buf)
  988. case "EC PRIVATE KEY":
  989. return x509.ParseECPrivateKey(buf)
  990. case "DSA PRIVATE KEY":
  991. return ParseDSAPrivateKey(buf)
  992. default:
  993. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  994. }
  995. }
  996. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  997. // specified by the OpenSSL DSA man page.
  998. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  999. var k struct {
  1000. Version int
  1001. P *big.Int
  1002. Q *big.Int
  1003. G *big.Int
  1004. Pub *big.Int
  1005. Priv *big.Int
  1006. }
  1007. rest, err := asn1.Unmarshal(der, &k)
  1008. if err != nil {
  1009. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  1010. }
  1011. if len(rest) > 0 {
  1012. return nil, errors.New("ssh: garbage after DSA key")
  1013. }
  1014. return &dsa.PrivateKey{
  1015. PublicKey: dsa.PublicKey{
  1016. Parameters: dsa.Parameters{
  1017. P: k.P,
  1018. Q: k.Q,
  1019. G: k.G,
  1020. },
  1021. Y: k.Pub,
  1022. },
  1023. X: k.Priv,
  1024. }, nil
  1025. }
  1026. // Implemented based on the documentation at
  1027. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
  1028. func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
  1029. const magic = "openssh-key-v1\x00"
  1030. if len(key) < len(magic) || string(key[:len(magic)]) != magic {
  1031. return nil, errors.New("ssh: invalid openssh private key format")
  1032. }
  1033. remaining := key[len(magic):]
  1034. var w struct {
  1035. CipherName string
  1036. KdfName string
  1037. KdfOpts string
  1038. NumKeys uint32
  1039. PubKey []byte
  1040. PrivKeyBlock []byte
  1041. }
  1042. if err := Unmarshal(remaining, &w); err != nil {
  1043. return nil, err
  1044. }
  1045. if w.KdfName != "none" || w.CipherName != "none" {
  1046. return nil, errors.New("ssh: cannot decode encrypted private keys")
  1047. }
  1048. pk1 := struct {
  1049. Check1 uint32
  1050. Check2 uint32
  1051. Keytype string
  1052. Rest []byte `ssh:"rest"`
  1053. }{}
  1054. if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil {
  1055. return nil, err
  1056. }
  1057. if pk1.Check1 != pk1.Check2 {
  1058. return nil, errors.New("ssh: checkint mismatch")
  1059. }
  1060. // we only handle ed25519 and rsa keys currently
  1061. switch pk1.Keytype {
  1062. case KeyAlgoRSA:
  1063. // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773
  1064. key := struct {
  1065. N *big.Int
  1066. E *big.Int
  1067. D *big.Int
  1068. Iqmp *big.Int
  1069. P *big.Int
  1070. Q *big.Int
  1071. Comment string
  1072. Pad []byte `ssh:"rest"`
  1073. }{}
  1074. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1075. return nil, err
  1076. }
  1077. for i, b := range key.Pad {
  1078. if int(b) != i+1 {
  1079. return nil, errors.New("ssh: padding not as expected")
  1080. }
  1081. }
  1082. pk := &rsa.PrivateKey{
  1083. PublicKey: rsa.PublicKey{
  1084. N: key.N,
  1085. E: int(key.E.Int64()),
  1086. },
  1087. D: key.D,
  1088. Primes: []*big.Int{key.P, key.Q},
  1089. }
  1090. if err := pk.Validate(); err != nil {
  1091. return nil, err
  1092. }
  1093. pk.Precompute()
  1094. return pk, nil
  1095. case KeyAlgoED25519:
  1096. key := struct {
  1097. Pub []byte
  1098. Priv []byte
  1099. Comment string
  1100. Pad []byte `ssh:"rest"`
  1101. }{}
  1102. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1103. return nil, err
  1104. }
  1105. if len(key.Priv) != ed25519.PrivateKeySize {
  1106. return nil, errors.New("ssh: private key unexpected length")
  1107. }
  1108. for i, b := range key.Pad {
  1109. if int(b) != i+1 {
  1110. return nil, errors.New("ssh: padding not as expected")
  1111. }
  1112. }
  1113. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  1114. copy(pk, key.Priv)
  1115. return &pk, nil
  1116. default:
  1117. return nil, errors.New("ssh: unhandled key type")
  1118. }
  1119. }
  1120. // FingerprintLegacyMD5 returns the user presentation of the key's
  1121. // fingerprint as described by RFC 4716 section 4.
  1122. func FingerprintLegacyMD5(pubKey PublicKey) string {
  1123. md5sum := md5.Sum(pubKey.Marshal())
  1124. hexarray := make([]string, len(md5sum))
  1125. for i, c := range md5sum {
  1126. hexarray[i] = hex.EncodeToString([]byte{c})
  1127. }
  1128. return strings.Join(hexarray, ":")
  1129. }
  1130. // FingerprintSHA256 returns the user presentation of the key's
  1131. // fingerprint as unpadded base64 encoded sha256 hash.
  1132. // This format was introduced from OpenSSH 6.8.
  1133. // https://www.openssh.com/txt/release-6.8
  1134. // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
  1135. func FingerprintSHA256(pubKey PublicKey) string {
  1136. sha256sum := sha256.Sum256(pubKey.Marshal())
  1137. hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
  1138. return "SHA256:" + hash
  1139. }