From 429358fd36067161dce759be35b41323d77d66b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20David=20C=C3=A9ry?= <73773471+philippecery@users.noreply.github.com> Date: Fri, 13 Nov 2020 15:40:38 +0800 Subject: [PATCH] more accurate error message --- pkcs8.go | 2 +- pkcs8_test.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/pkcs8.go b/pkcs8.go index f27f627..45b6d6a 100644 --- a/pkcs8.go +++ b/pkcs8.go @@ -143,7 +143,7 @@ func ParsePrivateKey(der []byte, password []byte) (interface{}, KDFParameters, e // Use the password provided to decrypt the private key var privKey encryptedPrivateKeyInfo if _, err := asn1.Unmarshal(der, &privKey); err != nil { - return nil, nil, errors.New("pkcs8: only PKCS #5 v2.0 supported") + return nil, nil, errors.New("pkcs8: failed to parse encrypted private key (make sure you passed the DER as the first parameter)") } if !privKey.EncryptionAlgorithm.Algorithm.Equal(oidPBES2) { diff --git a/pkcs8_test.go b/pkcs8_test.go index b0dd953..31fc041 100644 --- a/pkcs8_test.go +++ b/pkcs8_test.go @@ -343,6 +343,64 @@ func TestParsePKCS8PrivateKey(t *testing.T) { } } +func TestParsePKCS8PrivateKeyInvalidDER(t *testing.T) { + keyList := []struct { + name string + encrypted string + password string + }{ + { + name: "encryptedRSA2048aes", + encrypted: encryptedRSA2048aes, + password: "password", + }, + { + name: "encryptedRSA2048des3", + encrypted: encryptedRSA2048des3, + password: "password", + }, + { + name: "encryptedRSA2048scrypt", + encrypted: encryptedRSA2048scrypt, + password: "password", + }, + { + name: "encryptedEC256aes", + encrypted: encryptedEC256aes, + password: "password", + }, + { + name: "encryptedEC256aes128sha1", + encrypted: encryptedEC256aes128sha1, + password: "password", + }, + { + name: "encryptedRFCscrypt", + encrypted: encryptedRFCscrypt, + password: "Rabbit", + }, + { + name: "encryptedEC128aes", + encrypted: encryptedEC128aes, + password: "password", + }, + } + expectedError := "pkcs8: failed to parse encrypted private key (make sure you passed the DER as the first parameter)" + + for i, key := range keyList { + t.Run(key.name, func(t *testing.T) { + _, err := pkcs8.ParsePKCS8PrivateKey([]byte(key.encrypted), []byte(key.password)) + if err == nil { + t.Errorf("%d: should have failed", i) + } else { + if err.Error() != expectedError { + t.Errorf("Expected error \"%s\", got \"%s\"", expectedError, err.Error()) + } + } + }) + } +} + func TestConvertPrivateKeyToPKCS8(t *testing.T) { for i, password := range [][]byte{nil, []byte("password")} { var args [][]byte