@@ -13,6 +13,7 @@ import (
1313 "fmt"
1414 "io"
1515 "net/url"
16+ "slices"
1617 "strconv"
1718 "strings"
1819 "sync"
@@ -164,6 +165,17 @@ func openCard(card string) (pivKey, error) {
164165 return yk , nil
165166}
166167
168+ // validManagementKeyLengths contains the valid lengths
169+ // a YubiKey management key can have:
170+ // - 16 bytes for AES128
171+ // - 24 bytes for AES192 and DES3
172+ // - 32 bytes for AES256
173+ var validManagementKeyLengths = []int {16 , 24 , 32 }
174+
175+ // maximumManagementKeyLength is the maximum length a
176+ // Yubikey management key can have.
177+ const maximumManagementKeyLength = 32
178+
167179// New initializes a new YubiKey KMS.
168180//
169181// The most common way to open a YubiKey is to add a URI in the options:
@@ -189,7 +201,11 @@ func openCard(card string) (pivKey, error) {
189201// ones.
190202func New (_ context.Context , opts apiv1.Options ) (* YubiKey , error ) {
191203 pin := "123456"
192- managementKey := piv .DefaultManagementKey
204+ var managementKey [maximumManagementKeyLength ]byte
205+
206+ // set the default management key
207+ managementKeyLength := len (piv .DefaultManagementKey )
208+ copy (managementKey [:managementKeyLength ], piv .DefaultManagementKey )
193209
194210 var serial string
195211 if opts .URI != "" {
@@ -222,10 +238,11 @@ func New(_ context.Context, opts apiv1.Options) (*YubiKey, error) {
222238 if err != nil {
223239 return nil , errors .Wrap (err , "error decoding management key" )
224240 }
225- if len (b ) != 24 {
226- return nil , errors .New ("invalid managementKey: length is not 24 bytes" )
241+ managementKeyLength = len (b )
242+ if ! slices .Contains (validManagementKeyLengths , managementKeyLength ) {
243+ return nil , fmt .Errorf ("invalid management key length %d; expected 16, 24 or 32 bytes" , managementKeyLength )
227244 }
228- copy (managementKey , b [:24 ])
245+ copy (managementKey [: managementKeyLength ] , b [:managementKeyLength ])
229246 }
230247
231248 if opts .Pin != "" {
@@ -266,7 +283,7 @@ func New(_ context.Context, opts apiv1.Options) (*YubiKey, error) {
266283 yk : yk ,
267284 pin : pin ,
268285 card : card ,
269- managementKey : managementKey ,
286+ managementKey : managementKey [: managementKeyLength ] ,
270287 }, nil
271288}
272289
0 commit comments