1package types
 2
 3import (
 4	"fmt"
 5	"strings"
 6	"time"
 7
 8	"golang.org/x/crypto/ssh"
 9)
10
11var _ ssh.PublicKey = &PublicKey{}
12var _ fmt.Stringer = &PublicKey{}
13
14// PublicKey is a public key database model.
15type PublicKey struct {
16	ID        int
17	UserID    int
18	PublicKey string
19	CreatedAt *time.Time
20	UpdatedAt *time.Time
21}
22
23func (k *PublicKey) publicKey() ssh.PublicKey {
24	pk, err := ssh.ParsePublicKey([]byte(k.PublicKey))
25	if err != nil {
26		return nil
27	}
28	return pk
29}
30
31func (k *PublicKey) String() string {
32	pk := k.publicKey()
33	if pk == nil {
34		return ""
35	}
36	return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pk)))
37}
38
39// Type returns the type of the public key.
40func (k *PublicKey) Type() string {
41	pk := k.publicKey()
42	if pk == nil {
43		return ""
44	}
45	return pk.Type()
46}
47
48// Marshal returns the serialized form of the public key.
49func (k *PublicKey) Marshal() []byte {
50	pk := k.publicKey()
51	if pk == nil {
52		return nil
53	}
54	return pk.Marshal()
55}
56
57// Verify verifies the signature of the given data.
58func (k *PublicKey) Verify(data []byte, sig *ssh.Signature) error {
59	pk := k.publicKey()
60	if pk == nil {
61		return fmt.Errorf("invalid public key")
62	}
63	return pk.Verify(data, sig)
64}