@@ -15,3 +15,108 @@ limitations under the License.
15
15
*/
16
16
17
17
package utils
18
+
19
+ import (
20
+ "crypto"
21
+ "crypto/ecdsa"
22
+ "crypto/elliptic"
23
+ "crypto/rand"
24
+ "crypto/rsa"
25
+ b64 "encoding/base64"
26
+ "testing"
27
+
28
+ "github.com/stretchr/testify/assert"
29
+ "sigs.k8s.io/node-feature-discovery/pkg/apis/nfd/v1alpha1"
30
+ )
31
+
32
+ func mockNFRSpec () v1alpha1.NodeFeatureSpec {
33
+ return v1alpha1.NodeFeatureSpec {
34
+ Features : v1alpha1.Features {
35
+ Flags : map [string ]v1alpha1.FlagFeatureSet {
36
+ "test" : {
37
+ Elements : map [string ]v1alpha1.Nil {
38
+ "test2" : {},
39
+ },
40
+ },
41
+ },
42
+ },
43
+ }
44
+ }
45
+
46
+ func mockWorkerECDSAPrivateKey () (* ecdsa.PrivateKey , * ecdsa.PublicKey ) {
47
+ privateKey , _ := ecdsa .GenerateKey (elliptic .P384 (), rand .Reader )
48
+ return privateKey , & privateKey .PublicKey
49
+ }
50
+
51
+ func mockWorkerRSAPrivateKey () (* rsa.PrivateKey , * rsa.PublicKey ) {
52
+ privateKey , _ := rsa .GenerateKey (rand .Reader , 4096 )
53
+ return privateKey , & privateKey .PublicKey
54
+ }
55
+
56
+ func TestVerify (t * testing.T ) {
57
+ rsaPrivateKey , rsaPublicKey := mockWorkerRSAPrivateKey ()
58
+ ecdsaPrivateKey , ecdsaPublicKey := mockWorkerECDSAPrivateKey ()
59
+ spec := mockNFRSpec ()
60
+
61
+ tc := []struct {
62
+ name string
63
+ privateKey crypto.Signer
64
+ publicKey crypto.PublicKey
65
+ wantErr bool
66
+ }{
67
+ {
68
+ name : "RSA Keys" ,
69
+ privateKey : rsaPrivateKey ,
70
+ publicKey : rsaPublicKey ,
71
+ wantErr : true ,
72
+ },
73
+ {
74
+ name : "ECDSA Keys" ,
75
+ privateKey : ecdsaPrivateKey ,
76
+ publicKey : ecdsaPublicKey ,
77
+ wantErr : false ,
78
+ },
79
+ }
80
+
81
+ for _ , tt := range tc {
82
+ signedData , err := SignData (spec , tt .privateKey )
83
+ assert .NoError (t , err )
84
+
85
+ isVerified , err := VerifyDataSignature (spec , b64 .StdEncoding .EncodeToString (signedData ), tt .privateKey , tt .publicKey )
86
+ assert .NoError (t , err )
87
+ assert .True (t , isVerified )
88
+
89
+ signedData = append (signedData , "random" ... )
90
+ isVerified , err = VerifyDataSignature (spec , b64 .StdEncoding .EncodeToString (signedData ), tt .privateKey , tt .publicKey )
91
+ if tt .wantErr {
92
+ assert .Error (t , err )
93
+ } else {
94
+ assert .False (t , isVerified )
95
+ }
96
+ }
97
+ }
98
+
99
+ func TestSignData (t * testing.T ) {
100
+ rsaPrivateKey , _ := mockWorkerRSAPrivateKey ()
101
+ ecdsaPrivateKey , _ := mockWorkerECDSAPrivateKey ()
102
+ spec := mockNFRSpec ()
103
+
104
+ tc := []struct {
105
+ name string
106
+ privateKey crypto.Signer
107
+ }{
108
+ {
109
+ name : "RSA Keys" ,
110
+ privateKey : rsaPrivateKey ,
111
+ },
112
+ {
113
+ name : "ECDSA Keys" ,
114
+ privateKey : ecdsaPrivateKey ,
115
+ },
116
+ }
117
+
118
+ for _ , tt := range tc {
119
+ _ , err := SignData (spec , tt .privateKey )
120
+ assert .NoError (t , err )
121
+ }
122
+ }
0 commit comments