|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: BUSL-1.1 |
| 3 | + |
| 4 | +package pki |
| 5 | + |
| 6 | +import ( |
| 7 | + "crypto" |
| 8 | + "crypto/ecdsa" |
| 9 | + "crypto/ed25519" |
| 10 | + "crypto/elliptic" |
| 11 | + "crypto/rand" |
| 12 | + "crypto/rsa" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "github.com/hashicorp/vault/sdk/helper/certutil" |
| 16 | +) |
| 17 | + |
| 18 | +func TestGetKeyTypeAndBitsFromPublicKeyForRole(t *testing.T) { |
| 19 | + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) |
| 20 | + if err != nil { |
| 21 | + t.Fatalf("error generating rsa key: %s", err) |
| 22 | + } |
| 23 | + |
| 24 | + ecdsaKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) |
| 25 | + if err != nil { |
| 26 | + t.Fatalf("error generating ecdsa key: %s", err) |
| 27 | + } |
| 28 | + |
| 29 | + publicKey, _, err := ed25519.GenerateKey(rand.Reader) |
| 30 | + if err != nil { |
| 31 | + t.Fatalf("error generating ed25519 key: %s", err) |
| 32 | + } |
| 33 | + |
| 34 | + testCases := map[string]struct { |
| 35 | + publicKey crypto.PublicKey |
| 36 | + expectedKeyType certutil.PrivateKeyType |
| 37 | + expectedKeyBits int |
| 38 | + expectError bool |
| 39 | + }{ |
| 40 | + "rsa": { |
| 41 | + publicKey: rsaKey.Public(), |
| 42 | + expectedKeyType: certutil.RSAPrivateKey, |
| 43 | + expectedKeyBits: 2048, |
| 44 | + }, |
| 45 | + "ecdsa": { |
| 46 | + publicKey: ecdsaKey.Public(), |
| 47 | + expectedKeyType: certutil.ECPrivateKey, |
| 48 | + expectedKeyBits: 0, |
| 49 | + }, |
| 50 | + "ed25519": { |
| 51 | + publicKey: publicKey, |
| 52 | + expectedKeyType: certutil.Ed25519PrivateKey, |
| 53 | + expectedKeyBits: 0, |
| 54 | + }, |
| 55 | + "bad key type": { |
| 56 | + publicKey: []byte{}, |
| 57 | + expectedKeyType: certutil.UnknownPrivateKey, |
| 58 | + expectedKeyBits: 0, |
| 59 | + expectError: true, |
| 60 | + }, |
| 61 | + } |
| 62 | + |
| 63 | + for name, tt := range testCases { |
| 64 | + t.Run(name, func(t *testing.T) { |
| 65 | + keyType, keyBits, err := getKeyTypeAndBitsFromPublicKeyForRole(tt.publicKey) |
| 66 | + if err != nil && !tt.expectError { |
| 67 | + t.Fatalf("unexpected error: %s", err) |
| 68 | + } |
| 69 | + if err == nil && tt.expectError { |
| 70 | + t.Fatal("expected error, got nil") |
| 71 | + } |
| 72 | + |
| 73 | + if keyType != tt.expectedKeyType { |
| 74 | + t.Fatalf("key type mismatch: expected %s, got %s", tt.expectedKeyType, keyType) |
| 75 | + } |
| 76 | + |
| 77 | + if keyBits != tt.expectedKeyBits { |
| 78 | + t.Fatalf("key bits mismatch: expected %d, got %d", tt.expectedKeyBits, keyBits) |
| 79 | + } |
| 80 | + }) |
| 81 | + } |
| 82 | +} |
0 commit comments