generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdsa.go
84 lines (75 loc) · 2.47 KB
/
dsa.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
package dsa
import (
"fmt"
"github.com/tbd54566975/web5-go/crypto/dsa/ecdsa"
"github.com/tbd54566975/web5-go/crypto/dsa/eddsa"
"github.com/tbd54566975/web5-go/jwk"
)
const (
AlgorithmIDSECP256K1 = ecdsa.SECP256K1AlgorithmID
AlgorithmIDED25519 = eddsa.ED25519AlgorithmID
)
// GeneratePrivateKey generates a private key using the algorithm specified by algorithmID.
func GeneratePrivateKey(algorithmID string) (jwk.JWK, error) {
if ecdsa.SupportsAlgorithmID(algorithmID) {
return ecdsa.GeneratePrivateKey(algorithmID)
} else if eddsa.SupportsAlgorithmID(algorithmID) {
return eddsa.GeneratePrivateKey(algorithmID)
} else {
return jwk.JWK{}, fmt.Errorf("unsupported algorithm: %s", algorithmID)
}
}
// GetPublicKey returns the public key corresponding to the given private key.
func GetPublicKey(privateKey jwk.JWK) jwk.JWK {
switch privateKey.KTY {
case ecdsa.KeyType:
return ecdsa.GetPublicKey(privateKey)
case eddsa.KeyType:
return eddsa.GetPublicKey(privateKey)
default:
return jwk.JWK{}
}
}
// Sign signs the payload using the given private key.
func Sign(payload []byte, jwk jwk.JWK) ([]byte, error) {
switch jwk.KTY {
case ecdsa.KeyType:
return ecdsa.Sign(payload, jwk)
case eddsa.KeyType:
return eddsa.Sign(payload, jwk)
default:
return nil, fmt.Errorf("unsupported key type: %s", jwk.KTY)
}
}
// Verify verifies the signature of the payload using the given public key.
func Verify(payload []byte, signature []byte, jwk jwk.JWK) (bool, error) {
switch jwk.KTY {
case ecdsa.KeyType:
return ecdsa.Verify(payload, signature, jwk)
case eddsa.KeyType:
return eddsa.Verify(payload, signature, jwk)
default:
return false, fmt.Errorf("unsupported key type: %s", jwk.KTY)
}
}
// GetJWA returns the JWA (JSON Web Algorithm) algorithm corresponding to the given key.
func GetJWA(jwk jwk.JWK) (string, error) {
switch jwk.KTY {
case ecdsa.KeyType:
return ecdsa.GetJWA(jwk)
case eddsa.KeyType:
return eddsa.GetJWA(jwk)
default:
return "", fmt.Errorf("unsupported key type: %s", jwk.KTY)
}
}
// BytesToPublicKey converts the given bytes to a public key based on the algorithm specified by algorithmID.
func BytesToPublicKey(algorithmID string, input []byte) (jwk.JWK, error) {
if ecdsa.SupportsAlgorithmID(algorithmID) {
return ecdsa.BytesToPublicKey(algorithmID, input)
} else if eddsa.SupportsAlgorithmID(algorithmID) {
return eddsa.BytesToPublicKey(algorithmID, input)
} else {
return jwk.JWK{}, fmt.Errorf("unsupported algorithm: %s", algorithmID)
}
}