/
signer_eddsa.go
85 lines (68 loc) · 1.84 KB
/
signer_eddsa.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package pkcs7
import (
"errors"
"crypto"
"crypto/rand"
"crypto/ed25519"
"encoding/asn1"
)
// EdDsa 签名
type KeySignWithEdDSA struct {
hashFunc crypto.Hash
hashId asn1.ObjectIdentifier
identifier asn1.ObjectIdentifier
}
// oid
func (this KeySignWithEdDSA) HashOID() asn1.ObjectIdentifier {
return this.hashId
}
// oid
func (this KeySignWithEdDSA) OID() asn1.ObjectIdentifier {
return this.identifier
}
// 签名
func (this KeySignWithEdDSA) Sign(pkey crypto.PrivateKey, data []byte) ([]byte, []byte, error) {
var priv ed25519.PrivateKey
var ok bool
if priv, ok = pkey.(ed25519.PrivateKey); !ok {
return nil, nil, errors.New("pkcs7: PrivateKey is not ed25519 PrivateKey")
}
isHash := false
hashData := data
if this.hashFunc == crypto.SHA512 {
hashData = hashSignData(this.hashFunc, data)
isHash = true
}
signData, err := priv.Sign(rand.Reader, hashData, crypto.Hash(0))
if err != nil {
return nil, nil, err
}
var hashedData []byte
if isHash {
hashedData = hashData
}
return hashedData, signData, nil
}
// 验证
func (this KeySignWithEdDSA) Verify(pkey crypto.PublicKey, signed []byte, signature []byte) (bool, error) {
var pub ed25519.PublicKey
var ok bool
if pub, ok = pkey.(ed25519.PublicKey); !ok {
return false, errors.New("pkcs7: PublicKey is not ed25519 PublicKey")
}
hashData := signed
if this.hashFunc == crypto.SHA512 {
hashData = hashSignData(this.hashFunc, signed)
}
return ed25519.Verify(pub, hashData, signature), nil
}
// 检测证书
func (this KeySignWithEdDSA) Check(pkey any) bool {
if _, ok := pkey.(ed25519.PrivateKey); ok {
return true
}
if _, ok := pkey.(ed25519.PublicKey); ok {
return true
}
return false
}