From 0c5772714e5dd5f5f49cafd304452d7efce52a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Mur=C3=A9?= Date: Wed, 9 Jul 2025 18:37:40 +0200 Subject: [PATCH] crypto: catch potential wrong private key type from DER --- crypto/ed25519/private.go | 6 +++++- crypto/p256/private.go | 5 ++++- crypto/p384/private.go | 5 ++++- crypto/p521/private.go | 5 ++++- crypto/x25519/private.go | 5 ++++- 5 files changed, 21 insertions(+), 5 deletions(-) diff --git a/crypto/ed25519/private.go b/crypto/ed25519/private.go index 7c66b9c..12b462b 100644 --- a/crypto/ed25519/private.go +++ b/crypto/ed25519/private.go @@ -43,7 +43,11 @@ func PrivateKeyFromPKCS8DER(bytes []byte) (PrivateKey, error) { if err != nil { return PrivateKey{}, err } - return PrivateKey{k: priv.(ed25519.PrivateKey)}, nil + edPriv, ok := priv.(ed25519.PrivateKey) + if !ok { + return PrivateKey{}, fmt.Errorf("invalid private key type") + } + return PrivateKey{k: edPriv}, nil } // PrivateKeyFromPKCS8PEM decodes an PKCS#8 PEM (string) encoded private key. diff --git a/crypto/p256/private.go b/crypto/p256/private.go index b50900d..b921fec 100644 --- a/crypto/p256/private.go +++ b/crypto/p256/private.go @@ -48,7 +48,10 @@ func PrivateKeyFromPKCS8DER(bytes []byte) (*PrivateKey, error) { if err != nil { return nil, err } - ecdsaPriv := priv.(*ecdsa.PrivateKey) + ecdsaPriv, ok := priv.(*ecdsa.PrivateKey) + if !ok { + return nil, fmt.Errorf("invalid private key type") + } return &PrivateKey{k: ecdsaPriv}, nil } diff --git a/crypto/p384/private.go b/crypto/p384/private.go index ccdc5dc..ddbd255 100644 --- a/crypto/p384/private.go +++ b/crypto/p384/private.go @@ -48,7 +48,10 @@ func PrivateKeyFromPKCS8DER(bytes []byte) (*PrivateKey, error) { if err != nil { return nil, err } - ecdsaPriv := priv.(*ecdsa.PrivateKey) + ecdsaPriv, ok := priv.(*ecdsa.PrivateKey) + if !ok { + return nil, fmt.Errorf("invalid private key type") + } return &PrivateKey{k: ecdsaPriv}, nil } diff --git a/crypto/p521/private.go b/crypto/p521/private.go index fe2259d..b8e8621 100644 --- a/crypto/p521/private.go +++ b/crypto/p521/private.go @@ -48,7 +48,10 @@ func PrivateKeyFromPKCS8DER(bytes []byte) (*PrivateKey, error) { if err != nil { return nil, err } - ecdsaPriv := priv.(*ecdsa.PrivateKey) + ecdsaPriv, ok := priv.(*ecdsa.PrivateKey) + if !ok { + return nil, fmt.Errorf("invalid private key type") + } return &PrivateKey{k: ecdsaPriv}, nil } diff --git a/crypto/x25519/private.go b/crypto/x25519/private.go index 63b692f..56291a7 100644 --- a/crypto/x25519/private.go +++ b/crypto/x25519/private.go @@ -53,7 +53,10 @@ func PrivateKeyFromPKCS8DER(bytes []byte) (*PrivateKey, error) { if err != nil { return nil, err } - ecdhPriv := priv.(*ecdh.PrivateKey) + ecdhPriv, ok := priv.(*ecdh.PrivateKey) + if !ok { + return nil, fmt.Errorf("invalid private key type") + } return &PrivateKey{k: ecdhPriv}, nil }