miaopanel
1package plugins
2
3import (
4 "crypto/ed25519"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "os"
12 "strings"
13)
14
15const sigPrefix = "ed25519:"
16
17func parsePublic(raw string) (ed25519.PublicKey, error) {
18 raw = strings.TrimSpace(raw)
19 raw = strings.TrimPrefix(raw, sigPrefix)
20 buf, err := base64.StdEncoding.DecodeString(raw)
21 if err != nil || len(buf) != ed25519.PublicKeySize {
22 return nil, errors.New("公钥格式错误")
23 }
24 return ed25519.PublicKey(buf), nil
25}
26
27// verifySig checks a detached Ed25519 signature in "ed25519:<base64>" form.
28func verifySig(pubkey, signature string, data []byte) error {
29 pub, err := parsePublic(pubkey)
30 if err != nil {
31 return err
32 }
33 sig := strings.TrimPrefix(strings.TrimSpace(signature), sigPrefix)
34 raw, err := base64.StdEncoding.DecodeString(sig)
35 if err != nil || len(raw) != ed25519.SignatureSize {
36 return errors.New("签名格式错误")
37 }
38 if !ed25519.Verify(pub, data, raw) {
39 return errors.New("签名校验失败")
40 }
41 return nil
42}
43
44// artifactPayload is what the developer signs. It must match the cloud helper
45// byte for byte.
46func artifactPayload(slug, version, sha string) []byte {
47 return []byte(fmt.Sprintf("mp-plugin-v1\n%s\n%s\n%s\n", slug, version, strings.ToLower(sha)))
48}
49
50// hashFile returns the lowercase hex SHA-256 of a file.
51func hashFile(path string) (string, error) {
52 f, err := os.Open(path)
53 if err != nil {
54 return "", err
55 }
56 defer f.Close()
57 h := sha256.New()
58 if _, err := io.Copy(h, f); err != nil {
59 return "", err
60 }
61 return hex.EncodeToString(h.Sum(nil)), nil
62}