Skip to content

Commit 24e430f

Browse files
authored
crypto: ParseKey should not panic if key is empty (#45)
Signed-off-by: ItalyPaleAle <[email protected]>
1 parent e1fba87 commit 24e430f

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

crypto/keys.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ func SerializeKey(key jwk.Key) ([]byte, error) {
5151
// It supports keys represented as JWKs, PEM-encoded (PKCS#8, PKCS#1 or PKIX) or as raw bytes (optionally base64-encoded).
5252
// The parameter contentType is optional and it can contain a mime type.
5353
func ParseKey(raw []byte, contentType string) (jwk.Key, error) {
54+
l := len(raw)
55+
if l == 0 {
56+
return nil, errors.New("key is empty")
57+
}
58+
5459
// Determine the type of key if the type parameter is set
5560
switch contentType {
5661
case "application/json": // JWK
@@ -60,7 +65,6 @@ func ParseKey(raw []byte, contentType string) (jwk.Key, error) {
6065
}
6166

6267
// Heuristically determine the type of key
63-
l := len(raw)
6468
switch {
6569
case raw[0] == '{' && l != 16 && l != 24 && l != 32: // Assume it's a JWK unless the length is 16, 24, or 32 bytes
6670
return jwk.ParseKey(raw)

crypto/keys_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ import (
2626
"github.com/stretchr/testify/require"
2727
)
2828

29+
func TestEmptyKey(t *testing.T) {
30+
key, err := ParseKey([]byte{}, "")
31+
require.Error(t, err)
32+
require.EqualError(t, err, "key is empty")
33+
require.Nil(t, key)
34+
}
35+
2936
func TestSymmetricKeys(t *testing.T) {
3037
rawKey := make([]byte, 16)
3138
_, rawErr := io.ReadFull(rand.Reader, rawKey)

0 commit comments

Comments
 (0)