gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package asymkey
  4. import (
  5. "context"
  6. "fmt"
  7. "code.gitea.io/gitea/models/db"
  8. "golang.org/x/crypto/ssh"
  9. "xorm.io/builder"
  10. )
  11. // The database is used in checkKeyFingerprint. However, most of these functions probably belong in a module
  12. // checkKeyFingerprint only checks if key fingerprint has been used as a public key,
  13. // it is OK to use same key as deploy key for multiple repositories/users.
  14. func checkKeyFingerprint(ctx context.Context, fingerprint string) error {
  15. has, err := db.Exist[PublicKey](ctx, builder.Eq{"fingerprint": fingerprint})
  16. if err != nil {
  17. return err
  18. } else if has {
  19. return ErrKeyAlreadyExist{0, fingerprint, ""}
  20. }
  21. return nil
  22. }
  23. func calcFingerprintNative(publicKeyContent string) (string, error) {
  24. // Calculate fingerprint.
  25. pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyContent))
  26. if err != nil {
  27. return "", err
  28. }
  29. return ssh.FingerprintSHA256(pk), nil
  30. }
  31. // CalcFingerprint calculate public key's fingerprint
  32. func CalcFingerprint(publicKeyContent string) (string, error) {
  33. fp, err := calcFingerprintNative(publicKeyContent)
  34. if err != nil {
  35. if IsErrKeyUnableVerify(err) {
  36. return "", err
  37. }
  38. return "", fmt.Errorf("CalcFingerprint: %w", err)
  39. }
  40. return fp, nil
  41. }