Parsing of PKCS#8 encrypted private key files added and PKCS#12 basis

PKCS#8 encrypted key file support has been added to x509parse_key() with
support for some PCKS#12 PBE functions (pbeWithSHAAnd128BitRC4,
pbeWithSHAAnd3-KeyTripleDES-CBC and pbeWithSHAAnd2-KeyTripleDES-CBC)
(cherry picked from commit cf6e95d9a81c7b22271beb58a09b5c756148e62a)

Conflicts:
	scripts/generate_errors.pl
diff --git a/include/polarssl/config.h b/include/polarssl/config.h
index 3869654..0811e20 100644
--- a/include/polarssl/config.h
+++ b/include/polarssl/config.h
@@ -927,6 +927,22 @@
  */
 
 /**
+ * \def POLARSSL_PKCS12_C
+ *
+ * Enable PKCS#12 PBE functions
+ * Adds algorithms for parsing PKCS#8 encrypted private keys
+ *
+ * Module:  library/pkcs12.c
+ * Caller:  library/x509parse.c
+ *
+ * Requires: POLARSSL_ASN1_PARSE_C
+ * Can use:  POLARSSL_SHA1_C, POLARSSL_DES_C, POLARSSL_ARC4_C
+ *
+ * This module enables PKCS#12 functions.
+ */
+#define POLARSSL_PKCS12_C
+
+/**
  * \def POLARSSL_RSA_C
  *
  * Enable the RSA public-key cryptosystem.
diff --git a/include/polarssl/error.h b/include/polarssl/error.h
index cb8840c..9a3de00 100644
--- a/include/polarssl/error.h
+++ b/include/polarssl/error.h
@@ -76,6 +76,7 @@
  * High-level module nr (3 bits - 0x1...-0x8...)
  * Name     ID  Nr of Errors
  * PEM      1   9
+ * PKCS#12  1   3 (Started from top)
  * X509     2   21
  * DHM      3   6
  * RSA      4   9
diff --git a/include/polarssl/pkcs12.h b/include/polarssl/pkcs12.h
new file mode 100644
index 0000000..2a28c71
--- /dev/null
+++ b/include/polarssl/pkcs12.h
@@ -0,0 +1,139 @@
+/**
+ * \file pkcs12.h
+ *
+ * \brief PKCS#12 Personal Information Exchange Syntax
+ *
+ *  Copyright (C) 2006-2013, Brainspark B.V.
+ *
+ *  This file is part of PolarSSL (http://www.polarssl.org)
+ *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ *  All rights reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, write to the Free Software Foundation, Inc.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#ifndef POLARSSL_PKCS12_H
+#define POLARSSL_PKCS12_H
+
+#include <string.h>
+
+#include "md.h"
+#include "asn1.h"
+
+#define POLARSSL_ERR_PKCS12_BAD_INPUT_DATA                 -0x1F80  /**< Bad input parameters to function. */
+#define POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE            -0x1F00  /**< Feature not available, e.g. unsupported encryption scheme. */
+#define POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT             -0x1E80  /**< PBE ASN.1 data not as expected. */
+
+#define PKCS12_DERIVE_KEY       1   /*< encryption/decryption key */
+#define PKCS12_DERIVE_IV        2   /*< initialization vector     */
+#define PKCS12_DERIVE_MAC_KEY   3   /*< integrity / MAC key       */
+
+#define PKCS12_PBE_ENCRYPT      1
+#define PKCS12_PBE_DECRYPT      2
+
+/*
+ * PKCS#12 PBE types
+ */
+#define OID_PKCS12               "\x2a\x86\x48\x86\xf7\x0d\x01\x0c"
+#define OID_PKCS12_PBE_SHA1_RC4_128         OID_PKCS12 "\x01\x01"
+#define OID_PKCS12_PBE_SHA1_DES3_EDE_CBC    OID_PKCS12 "\x01\x03"
+#define OID_PKCS12_PBE_SHA1_DES2_EDE_CBC    OID_PKCS12 "\x01\x04"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief            PKCS12 Password Based function (encryption / decryption)
+ *                   for pbeWithSHAAnd128BitRC4
+ *
+ * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure
+ * \param mode       either PKCS12_PBE_ENCRYPT or PKCS12_PBE_DECRYPT
+ * \param pwd        the password used (may be NULL if no password is used)
+ * \param pwdlen     length of the password (may be 0)
+ * \param input      the input data
+ * \param len        data length
+ * \param output     the output buffer
+ */
+int pkcs12_pbe_sha1_rc4_128( asn1_buf *pbe_params, int mode,
+                             const unsigned char *pwd,  size_t pwdlen,
+                             const unsigned char *input, size_t len,
+                             unsigned char *output );
+
+/**
+ * \brief            PKCS12 Password Based function (encryption / decryption)
+ *                   for pbeWithSHAAnd3-KeyTripleDES-CBC
+ *
+ * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure
+ * \param mode       either PKCS12_PBE_ENCRYPT or PKCS12_PBE_DECRYPT
+ * \param pwd        the password used (may be NULL if no password is used)
+ * \param pwdlen     length of the password (may be 0)
+ * \param input      the input data
+ * \param len        data length
+ * \param output     the output buffer
+ */
+int pkcs12_pbe_sha1_des3_ede_cbc( asn1_buf *pbe_params, int mode,
+                                  const unsigned char *pwd,  size_t pwdlen,
+                                  const unsigned char *input, size_t len,
+                                  unsigned char *output );
+
+/**
+ * \brief            PKCS12 Password Based function (encryption / decryption)
+ *                   for pbeWithSHAAnd2-KeyTripleDES-CBC
+ *
+ * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure
+ * \param mode       either PKCS12_PBE_ENCRYPT or PKCS12_PBE_DECRYPT
+ * \param pwd        the password used (may be NULL if no password is used)
+ * \param pwdlen     length of the password (may be 0)
+ * \param input      the input data
+ * \param len        data length
+ * \param output     the output buffer
+ */
+int pkcs12_pbe_sha1_des2_ede_cbc( asn1_buf *pbe_params, int mode,
+                                  const unsigned char *pwd,  size_t pwdlen,
+                                  const unsigned char *input, size_t len,
+                                  unsigned char *output );
+
+/**
+ * \brief            The PKCS#12 derivation function uses a password and a salt
+ *                   to produce pseudo-random bits for a particular "purpose".
+ *
+ *                   Depending on the given id, this function can produce an
+ *                   encryption/decryption key, an nitialization vector or an
+ *                   integrity key.
+ *
+ * \param data       buffer to store the derived data in
+ * \param datalen    length to fill
+ * \param pwd        password to use (may be NULL if no password is used)
+ * \param pwdlen     length of the password (may be 0)
+ * \param salt       salt buffer to use
+ * \param saltlen    length of the salt
+ * \param md         md type to use during the derivation
+ * \param id         id that describes the purpose (can be PKCS12_DERIVE_KEY,
+ *                   PKCS12_DERIVE_IV or PKCS12_DERIVE_MAC_KEY)
+ * \param iterations number of iterations
+ *
+ * \return          0 if successful, or a MD, BIGNUM type error.
+ */
+int pkcs12_derivation( unsigned char *data, size_t datalen,
+                       const unsigned char *pwd, size_t pwdlen,
+                       const unsigned char *salt, size_t saltlen,
+                       md_type_t md, int id, int iterations );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* pkcs12.h */
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index a4b3113..5c0ecfb 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -35,6 +35,7 @@
      pbkdf2.c
      pem.c
      pkcs11.c
+     pkcs12.c
      rsa.c
      sha1.c
      sha2.c
diff --git a/library/Makefile b/library/Makefile
index e878583..72f8566 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -47,7 +47,7 @@
 		md4.o		md5.o		net.o			\
 		oid.o									\
 		padlock.o	pbkdf2.o	pem.o			\
-		pkcs11.o								\
+		pkcs11.o	pkcs12.o					\
 		rsa.o		sha1.o		sha2.o			\
 		sha4.o		ssl_cache.o	ssl_cli.o		\
 		ssl_srv.o   ssl_ciphersuites.o			\
diff --git a/library/error.c b/library/error.c
index fe2be91..fec8152 100644
--- a/library/error.c
+++ b/library/error.c
@@ -113,6 +113,10 @@
 #include "polarssl/pem.h"
 #endif
 
+#if defined(POLARSSL_PKCS12_C)
+#include "polarssl/pkcs12.h"
+#endif
+
 #if defined(POLARSSL_RSA_C)
 #include "polarssl/rsa.h"
 #endif
@@ -233,6 +237,15 @@
             snprintf( buf, buflen, "PEM - Bad input parameters to function" );
 #endif /* POLARSSL_PEM_C */
 
+#if defined(POLARSSL_PKCS12_C)
+        if( use_ret == -(POLARSSL_ERR_PKCS12_BAD_INPUT_DATA) )
+            snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" );
+        if( use_ret == -(POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE) )
+            snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" );
+        if( use_ret == -(POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT) )
+            snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" );
+#endif /* POLARSSL_PKCS12_C */
+
 #if defined(POLARSSL_RSA_C)
         if( use_ret == -(POLARSSL_ERR_RSA_BAD_INPUT_DATA) )
             snprintf( buf, buflen, "RSA - Bad input parameters to function" );
diff --git a/library/pkcs12.c b/library/pkcs12.c
new file mode 100644
index 0000000..39ab10f
--- /dev/null
+++ b/library/pkcs12.c
@@ -0,0 +1,363 @@
+/*
+ *  PKCS#12 Personal Information Exchange Syntax
+ *
+ *  Copyright (C) 2006-2013, Brainspark B.V.
+ *
+ *  This file is part of PolarSSL (http://www.polarssl.org)
+ *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ *  All rights reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, write to the Free Software Foundation, Inc.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+/*
+ *  The PKCS #12 Personal Information Exchange Syntax Standard v1.1
+ *
+ *  http://www.rsa.com/rsalabs/pkcs/files/h11301-wp-pkcs-12v1-1-personal-information-exchange-syntax.pdf
+ *  ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1-1.asn
+ */
+
+#include "polarssl/config.h"
+
+#if defined(POLARSSL_PKCS12_C)
+
+#include "polarssl/pkcs12.h"
+#include "polarssl/asn1.h"
+
+#if defined(POLARSSL_ARC4_C)
+#include "polarssl/arc4.h"
+#endif
+
+#if defined(POLARSSL_DES_C)
+#include "polarssl/des.h"
+#endif
+
+static int pkcs12_parse_pbe_params( unsigned char **p,
+                                    const unsigned char *end,
+                                    asn1_buf *salt, int *iterations )
+{
+    int ret;
+    size_t len = 0;
+
+    /*
+     *  pkcs-12PbeParams ::= SEQUENCE {
+     *    salt          OCTET STRING,
+     *    iterations    INTEGER
+     *  }
+     *
+     */
+    if( ( ret = asn1_get_tag( p, end, &len,
+            ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
+    {
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT + ret );
+    }
+
+    end = *p + len;
+
+    if( ( ret = asn1_get_tag( p, end, &salt->len, ASN1_OCTET_STRING ) ) != 0 )
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT + ret );
+
+    salt->p = *p;
+    *p += salt->len;
+
+    if( ( ret = asn1_get_int( p, end, iterations ) ) != 0 )
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT + ret );
+
+    if( *p != end )
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT +
+                POLARSSL_ERR_ASN1_LENGTH_MISMATCH );
+
+    return( 0 );
+}
+
+static int pkcs12_pbe_derive_key_iv( asn1_buf *pbe_params,
+                                     const unsigned char *pwd,  size_t pwdlen,
+                                     unsigned char *key, size_t keylen,
+                                     unsigned char *iv,  size_t ivlen )
+{
+    int ret, iterations;
+    asn1_buf salt;
+    size_t i;
+    unsigned char *p, *end;
+    unsigned char unipwd[258];
+
+    memset(&salt, 0, sizeof(asn1_buf));
+    memset(&unipwd, 0, sizeof(unipwd));
+
+    p = pbe_params->p;
+    end = p + pbe_params->len;
+
+    if( ( ret = pkcs12_parse_pbe_params( &p, end, &salt, &iterations ) ) != 0 )
+        return( ret );
+
+    for(i = 0; i < pwdlen; i++)
+        unipwd[i * 2 + 1] = pwd[i];
+
+    if( ( ret = pkcs12_derivation( key, keylen, unipwd, pwdlen * 2 + 2,
+                                   salt.p, salt.len, POLARSSL_MD_SHA1,
+                                   PKCS12_DERIVE_KEY, iterations ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    if( iv == NULL || ivlen == 0 )
+        return( 0 );
+
+    if( ( ret = pkcs12_derivation( iv, ivlen, unipwd, pwdlen * 2 + 2,
+                                   salt.p, salt.len, POLARSSL_MD_SHA1,
+                                   PKCS12_DERIVE_IV, iterations ) ) != 0 )
+    {
+        return( ret );
+    }
+    return( 0 );
+}
+
+int pkcs12_pbe_sha1_rc4_128( asn1_buf *pbe_params, int mode,
+                             const unsigned char *pwd,  size_t pwdlen,
+                             const unsigned char *data, size_t len,
+                             unsigned char *output )
+{
+#if !defined(POLARSSL_ARC4_C)
+    ((void) pbe_params);
+    ((void) mode);
+    ((void) pwd);
+    ((void) pwdlen);
+    ((void) data);
+    ((void) len);
+    ((void) output);
+    return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+#else
+    int ret;
+    unsigned char key[16];
+    arc4_context ctx;
+    ((void) mode);
+
+    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, pwd, pwdlen,
+                                          key, 16, NULL, 0 ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    arc4_setup( &ctx, key, 16 );
+    if( ( ret = arc4_crypt( &ctx, len, data, output ) ) != 0 )
+        return( ret );
+
+    return( 0 );
+}
+#endif /* POLARSSL_ARC4_C */
+
+int pkcs12_pbe_sha1_des2_ede_cbc( asn1_buf *pbe_params, int mode,
+                                  const unsigned char *pwd,  size_t pwdlen,
+                                  const unsigned char *data, size_t len,
+                                  unsigned char *output )
+{
+#if !defined(POLARSSL_DES_C)
+    ((void) pbe_params);
+    ((void) mode);
+    ((void) pwd);
+    ((void) pwdlen);
+    ((void) data);
+    ((void) len);
+    ((void) output);
+    return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+#else
+    int ret;
+    unsigned char key[16];
+    unsigned char iv[8];
+    des3_context ctx;
+
+    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, pwd, pwdlen,
+                                          key, 16, iv, 8 ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    if( mode == PKCS12_PBE_ENCRYPT )
+    {
+        des3_set2key_enc( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_ENCRYPT, len, iv, data, output );
+    }
+    else
+    {
+        des3_set2key_dec( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_DECRYPT, len, iv, data, output );
+    }
+
+    return( 0 );
+}
+#endif /* POLARSSL_DES_C */
+
+int pkcs12_pbe_sha1_des3_ede_cbc( asn1_buf *pbe_params, int mode,
+                                  const unsigned char *pwd,  size_t pwdlen,
+                                  const unsigned char *data, size_t len,
+                                  unsigned char *output )
+{
+#if !defined(POLARSSL_DES_C)
+    ((void) pbe_params);
+    ((void) mode);
+    ((void) pwd);
+    ((void) pwdlen);
+    ((void) data);
+    ((void) len);
+    ((void) output);
+    return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+#else
+    int ret;
+    unsigned char key[24];
+    unsigned char iv[8];
+    des3_context ctx;
+
+    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, pwd, pwdlen,
+                                          key, 24, iv, 8 ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    if( mode == PKCS12_PBE_ENCRYPT )
+    {
+        des3_set3key_enc( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_ENCRYPT, len, iv, data, output );
+    }
+    else
+    {
+        des3_set3key_dec( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_DECRYPT, len, iv, data, output );
+    }
+
+    return( 0 );
+}
+#endif /* POLARSSL_DES_C */
+
+static void pkcs12_fill_buffer( unsigned char *data, size_t data_len,
+                                const unsigned char *filler, size_t fill_len )
+{
+    unsigned char *p = data;
+    size_t use_len;
+
+    while( data_len > 0 )
+    {
+        use_len = ( data_len > fill_len ) ? fill_len : data_len;
+        memcpy( p, filler, use_len );
+        p += use_len;
+        data_len -= use_len;
+    }
+}
+
+int pkcs12_derivation( unsigned char *data, size_t datalen,
+                       const unsigned char *pwd, size_t pwdlen,
+                       const unsigned char *salt, size_t saltlen,
+                       md_type_t md_type, int id, int iterations )
+{
+    int ret, i;
+    unsigned int j;
+
+    unsigned char diversifier[128];
+    unsigned char salt_block[128], pwd_block[128], hash_block[128];
+    unsigned char hash_output[POLARSSL_MD_MAX_SIZE];
+    unsigned char *p;
+    unsigned char c;
+
+    size_t hlen, use_len, v;
+
+    const md_info_t *md_info;
+    md_context_t md_ctx;
+
+    // This version only allows max of 64 bytes of password or salt
+    if( datalen > 128 || pwdlen > 64 || saltlen > 64 )
+        return( POLARSSL_ERR_PKCS12_BAD_INPUT_DATA );
+
+    md_info = md_info_from_type( md_type );
+    if( md_info == NULL )
+        return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+
+    if ( ( ret = md_init_ctx( &md_ctx, md_info ) ) != 0 )
+        return( ret );
+    hlen = md_get_size( md_info );
+
+    if( hlen <= 32 )
+        v = 64;
+    else
+        v = 128;
+
+    memset( diversifier, (unsigned char) id, v );
+
+    pkcs12_fill_buffer( salt_block, v, salt, saltlen );
+    pkcs12_fill_buffer( pwd_block,  v, pwd,  pwdlen  );
+
+    p = data;
+    while( datalen > 0 )
+    {
+        // Calculate hash( diversifier || salt_block || pwd_block )
+        if( ( ret = md_starts( &md_ctx ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_update( &md_ctx, diversifier, v ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_update( &md_ctx, salt_block, v ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_update( &md_ctx, pwd_block, v ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_finish( &md_ctx, hash_output ) ) != 0 )
+            return( ret );
+
+        // Perform remaining ( iterations - 1 ) recursive hash calculations
+        for( i = 1; i < iterations; i++ )
+        {
+            if( ( ret = md( md_info, hash_output, hlen, hash_output ) ) != 0 )
+                return( ret );
+        }
+
+        use_len = ( datalen > hlen ) ? hlen : datalen;
+        memcpy( p, hash_output, use_len );
+        datalen -= use_len;
+        p += use_len;
+
+        if( datalen == 0 )
+            break;
+
+        // Concatenating copies of hash_output into hash_block (B)
+        pkcs12_fill_buffer( hash_block, v, hash_output, hlen );
+
+        // B += 1
+        for( i = v; i > 0; i-- )
+            if( ++hash_block[i - 1] != 0 )
+                break;
+
+        // salt_block += B
+        c = 0;
+        for( i = v; i > 0; i-- )
+        {
+            j = salt_block[i - 1] + hash_block[i - 1] + c;
+            c = (unsigned char) (j >> 8);
+            salt_block[i - 1] = j & 0xFF;
+        }
+
+        // pwd_block  += B
+        c = 0;
+        for( i = v; i > 0; i-- )
+        {
+            j = pwd_block[i - 1] + hash_block[i - 1] + c;
+            c = (unsigned char) (j >> 8);
+            pwd_block[i - 1] = j & 0xFF;
+        }
+    }
+
+    return( 0 );
+}
+
+#endif /* POLARSSL_PKCS12_C */
diff --git a/library/x509parse.c b/library/x509parse.c
index 23c57ea..bda8111 100644
--- a/library/x509parse.c
+++ b/library/x509parse.c
@@ -62,6 +62,7 @@
 #include "polarssl/sha4.h"
 #endif
 #include "polarssl/dhm.h"
+#include "polarssl/pkcs12.h"
 
 #include <string.h>
 #include <stdlib.h>
@@ -2170,6 +2171,116 @@
 }
 
 /*
+ * Parse an unencrypted PKCS#8 encoded private RSA key
+ */
+static int x509parse_key_pkcs8_encrypted_der(
+                                    rsa_context *rsa,
+                                    const unsigned char *key,
+                                    size_t keylen,
+                                    const unsigned char *pwd,
+                                    size_t pwdlen )
+{
+    int ret;
+    size_t len;
+    unsigned char *p, *end, *end2;
+    x509_buf pbe_alg_oid, pbe_params;
+    unsigned char buf[2048];
+
+    memset(buf, 0, 2048);
+
+    p = (unsigned char *) key;
+    end = p + keylen;
+
+    /*
+     * This function parses the EncryptedPrivatKeyInfo object (PKCS#8)
+     *
+     *  EncryptedPrivateKeyInfo ::= SEQUENCE {
+     *    encryptionAlgorithm  EncryptionAlgorithmIdentifier,
+     *    encryptedData        EncryptedData
+     *  }
+     *
+     *  EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+     *
+     *  EncryptedData ::= OCTET STRING
+     *
+     *  The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
+     */
+    if( ( ret = asn1_get_tag( &p, end, &len,
+            ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
+    {
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+    }
+
+    end = p + len;
+
+    if( ( ret = asn1_get_tag( &p, end, &len,
+            ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
+    {
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+    }
+
+    end2 = p + len;
+
+    if( ( ret = asn1_get_tag( &p, end, &pbe_alg_oid.len, ASN1_OID ) ) != 0 )
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+
+    pbe_alg_oid.p = p;
+    p += pbe_alg_oid.len;
+
+    /*
+     * Store the algorithm parameters
+     */
+    pbe_params.p = p;
+    pbe_params.len = end2 - p;
+    p += pbe_params.len;
+
+    if( ( ret = asn1_get_tag( &p, end, &len, ASN1_OCTET_STRING ) ) != 0 )
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+
+    // buf has been sized to 2048 bytes
+    if( len > 2048 )
+        return( POLARSSL_ERR_X509_INVALID_INPUT );
+
+    /*
+     * Decrypt EncryptedData with appropriate PDE
+     */
+    if( OID_CMP( OID_PKCS12_PBE_SHA1_DES3_EDE_CBC, &pbe_alg_oid ) )
+    {
+        if( ( ret = pkcs12_pbe_sha1_des3_ede_cbc( &pbe_params,
+                                                   PKCS12_PBE_DECRYPT,
+                                                   pwd, pwdlen,
+                                                   p, len, buf ) ) != 0 )
+        {
+            return( ret );
+        }
+    }
+    else if( OID_CMP( OID_PKCS12_PBE_SHA1_DES2_EDE_CBC, &pbe_alg_oid ) )
+    {
+        if( ( ret = pkcs12_pbe_sha1_des2_ede_cbc( &pbe_params,
+                                                   PKCS12_PBE_DECRYPT,
+                                                   pwd, pwdlen,
+                                                   p, len, buf ) ) != 0 )
+        {
+            return( ret );
+        }
+    }
+    else if( OID_CMP( OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) )
+    {
+        if( ( ret = pkcs12_pbe_sha1_rc4_128( &pbe_params,
+                                             PKCS12_PBE_DECRYPT,
+                                             pwd, pwdlen,
+                                             p, len, buf ) ) != 0 )
+        {
+            return( ret );
+        }
+    }
+    else
+        return( POLARSSL_ERR_X509_FEATURE_UNAVAILABLE );
+
+    return x509parse_key_pkcs8_unencrypted_der( rsa, buf, len );
+}
+
+/*
  * Parse a private RSA key
  */
 int x509parse_key( rsa_context *rsa, const unsigned char *key, size_t keylen,
@@ -2223,7 +2334,27 @@
         return( ret );
     }
 
-    pem_free( &pem );
+    ret = pem_read_buffer( &pem,
+                           "-----BEGIN ENCRYPTED PRIVATE KEY-----",
+                           "-----END ENCRYPTED PRIVATE KEY-----",
+                           key, NULL, 0, &len );
+    if( ret == 0 )
+    {
+        if( ( ret = x509parse_key_pkcs8_encrypted_der( rsa,
+                                                pem.buf, pem.buflen,
+                                                pwd, pwdlen ) ) != 0 )
+        {
+            rsa_free( rsa );
+        }
+
+        pem_free( &pem );
+        return( ret );
+    }
+    else if( ret != POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
+    {
+        pem_free( &pem );
+        return( ret );
+    }
 #else
     ((void) pwd);
     ((void) pwdlen);
@@ -2235,18 +2366,22 @@
     // We try the different DER format parsers to see if one passes without
     // error
     //
-    if( ( ret = x509parse_key_pkcs8_unencrypted_der( rsa, key, keylen ) ) != 0 )
+    if( ( ret = x509parse_key_pkcs8_encrypted_der( rsa, key, keylen,
+                                                   pwd, pwdlen ) ) == 0 )
     {
-        rsa_free( rsa );
-
-        if( ( ret = x509parse_key_pkcs1_der( rsa, key, keylen ) ) != 0 )
-        {
-            rsa_free( rsa );
-            return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT );
-        }
+        return( 0 );
     }
 
-    return( 0 );
+    rsa_free( rsa );
+    if( ( ret = x509parse_key_pkcs8_unencrypted_der( rsa, key, keylen ) ) == 0 )
+        return( 0 );
+
+    rsa_free( rsa );
+    if( ( ret = x509parse_key_pkcs1_der( rsa, key, keylen ) ) == 0 )
+        return( 0 );
+
+    rsa_free( rsa );
+    return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT );
 }
 
 /*
diff --git a/scripts/generate_errors.pl b/scripts/generate_errors.pl
index a225c63..e80072e 100755
--- a/scripts/generate_errors.pl
+++ b/scripts/generate_errors.pl
@@ -12,7 +12,8 @@
                           "BASE64", "XTEA", "PBKDF2", "OID",
                           "PADLOCK", "DES", "NET", "CTR_DRBG", "ENTROPY",
                           "MD2", "MD4", "MD5", "SHA1", "SHA2", "SHA4", "GCM" );
-my @high_level_modules = ( "PEM", "X509", "DHM", "RSA", "ECP", "MD", "CIPHER", "SSL" );
+my @high_level_modules = ( "PEM", "X509", "DHM", "RSA", "ECP", "MD", "CIPHER", "SSL",
+                           "PKCS12" );
 
 my $line_separator = $/;
 undef $/;
diff --git a/tests/data_files/pkcs8_pbe_sha1_2des.key b/tests/data_files/pkcs8_pbe_sha1_2des.key
new file mode 100644
index 0000000..4ae7aec
--- /dev/null
+++ b/tests/data_files/pkcs8_pbe_sha1_2des.key
@@ -0,0 +1,29 @@
+-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIIE6jAcBgoqhkiG9w0BDAEEMA4ECJUO+jJnTjpKAgIIAASCBMi9QFFLgKGYOSDR
+0zyRMc87RkrvSlyRi8BibyKvTNE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CJJ0M+glzHrJs3L+PiJMi
+gm+YT/5FuSqJZ/JI5QP7VMovqSLEw6y6QQHSBCOxh/CGhAL/BZ9A9afvPTRiI9OF
+fyxAaf8KH1YPI3uKIuDcms0d0gJqQoDmLafdfggd6dwuLF3iQpDORgx80oPbjfl1
+FEbU8M5DqiH+eOxgEvIL0AhMnPa4mv1brVdlxS3CyojnqxPfecXyEXrhEYJWJdsF
+aYKR5bU1bY990aN6T3EDRblmHs25Fc328xS2ZJkHNxcJDruwi4EFpQVT+fukOz00
+hOW2BEMFJLRflE+372LNIgSRVNI536YhF8r4r7O1jrw9McX3hzbJGAtcsXqyIO/k
+hxC3x5ViqgZbDYgHz/CJJfP2RC8spp2RbZ/uDJu2YI8z8s9OXvcYv0EQmBAJxdt/
+lyfkzEr/n8oRtDIkrq7lR3rjMUz7AbCfNJpqrEBFol9+qH8+jnmowL8LWBlh0v/A
+pc3qWIulXOR1pbwXyAELo8wGhnJWL4WmY252S3i0Jn8Gf2kXewMRJsixStairjWD
+1m0wWUVGSm5CO8Rfon8=
+-----END ENCRYPTED PRIVATE KEY-----
diff --git a/tests/data_files/pkcs8_pbe_sha1_3des.der b/tests/data_files/pkcs8_pbe_sha1_3des.der
new file mode 100644
index 0000000..f2ce029
--- /dev/null
+++ b/tests/data_files/pkcs8_pbe_sha1_3des.der
Binary files differ
diff --git a/tests/data_files/pkcs8_pbe_sha1_3des.key b/tests/data_files/pkcs8_pbe_sha1_3des.key
new file mode 100644
index 0000000..f9c11ad
--- /dev/null
+++ b/tests/data_files/pkcs8_pbe_sha1_3des.key
@@ -0,0 +1,29 @@
+-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIIE6jAcBgoqhkiG9w0BDAEDMA4ECGhNuQogiktrAgIIAASCBMhfcb+Jt0YOgGni
+IWnwmmtYT6Nvina/j3FCGzcHCDyUQDqh1rPUtZnmUdM3fyEGlUJdX9wmHh3gUkWx
+JE00QMzYDQsUbGrt8H3rCQ+aXegCicXAyBgDh0YUhO7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AmQT29EslB/3RcrWH3tZExJjjDaC+Ty2atCMmlLGxt7VHOa
+C3k0QHYSE/TULBldB64S1vVFrZgzLFTlXKGm38mOGCG3t/lQQDTo3IAp0YE+atM3
+VG6ON3SSU0QRP1aEkZY8t9rf3+/J8Nl8oF4kF9ISzLNhlR/KJlNkmDvG/ic0skJK
+KYezuuYH8/eEr9ZFfBsb9mRsFCM9iBZl/XqebCCC5/kfXzL/Hpp4f0L7DH4C0f6L
+LbMCFhvsCNGh+1pdIjN9hbAkv/r2NN8+MaY2xFk0ukLfKgpLp0EfpkkcM0EZcvFn
+j1JpB7rshCLj4PzM77fLh99H4cffL2qyzXqFF2Y7iW28bW/RQFxYwpyEnowrcRH/
+11Qi525SdKWRkb9QlTJqFI6wsWe5kmYO/kDqGUpGPGK8+XTRTFjTci7NPLqN+s0w
+Z4/b5SMVucBKq9sUm6g=
+-----END ENCRYPTED PRIVATE KEY-----
diff --git a/tests/data_files/pkcs8_pbe_sha1_rc4_128.key b/tests/data_files/pkcs8_pbe_sha1_rc4_128.key
new file mode 100644
index 0000000..d475ef4
--- /dev/null
+++ b/tests/data_files/pkcs8_pbe_sha1_rc4_128.key
@@ -0,0 +1,29 @@
+-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIIE4zAcBgoqhkiG9w0BDAEBMA4ECCLhzdwnOXIZAgIIAASCBMG8Wgfn++CFRl37
+FdQZ90pI+u37yj8v0kFd3rDaDMurEftf10gWwTbm8R8J0eK1edIAHQabkgsF83gD
+yrxKFp1zhHI1t65gPKHcirhx0t9XuClxAOzEme//iMaw/yf/IKYo9NRqyvA6BKHW
+2h3J4+JSGLSaCsRUyzhoL6xOzF+VX8zE8PI11TcqfJe7TGs/9G0Pv2XxFpfrG7pz
+nz5mkAYdckYHcu7+CQGJ09ZUkblV3MYKEEbq5xXEo4Kku/n1YNrh6BEWMLo5XgOU
+YIAkzhSfnbTt6QrxM+90b4qwk5amrC4w1jUu73ZzaBQs7fhx01pR2y3zTPBD2Dpk
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qRsRnWyGv9dVLIaQPwUS+eEfsGGNzM9rbty0j5Bw6KY/uDgt
+blTfN3yZBcyEsdPwyiVLdi65zMzN8g4VVQBHFhXWPa2N4gJQVq+6q9hQkgFFU7y3
+f8MX4BrKq8ifwWxsjL2FawcAoDcHUdCZjt/HZ+9/rL3iQvKeHbDbqu4kxlrE1FJn
+0LHIB21qZIo+6r3fdNMUFkuDRBT9eEh3Wxlg8G35FYCIiOuIwB2ED/Hdnqtnemxj
+kjRXU176HQ==
+-----END ENCRYPTED PRIVATE KEY-----
diff --git a/tests/suites/test_suite_x509parse.data b/tests/suites/test_suite_x509parse.data
index a562e56..19073e0 100644
--- a/tests/suites/test_suite_x509parse.data
+++ b/tests/suites/test_suite_x509parse.data
@@ -114,6 +114,22 @@
 depends_on:POLARSSL_MD5_C:POLARSSL_PEM_C:POLARSSL_FS_IO
 x509parse_keyfile:"data_files/format_gen.key":"":0
 
+X509 Parse Key #10 (PKCS#8 encrypted SHA1-3DES)
+depends_on:POLARSSL_DES_C:POLARSSL_SHA1_C:POLARSSL_PEM_C:POLARSSL_FS_IO
+x509parse_keyfile:"data_files/pkcs8_pbe_sha1_3des.key":"PolarSSLTest":0
+
+X509 Parse Key #11 (PKCS#8 encrypted SHA1-3DES DER)
+depends_on:POLARSSL_DES_C:POLARSSL_SHA1_C:POLARSSL_FS_IO
+x509parse_keyfile:"data_files/pkcs8_pbe_sha1_3des.der":"PolarSSLTest":0
+
+X509 Parse Key #12 (PKCS#8 encrypted SHA1-2DES)
+depends_on:POLARSSL_DES_C:POLARSSL_SHA1_C:POLARSSL_PEM_C:POLARSSL_FS_IO
+x509parse_keyfile:"data_files/pkcs8_pbe_sha1_2des.key":"PolarSSLTest":0
+
+X509 Parse Key #13 (PKCS#8 encrypted SHA1-RC4-128)
+depends_on:POLARSSL_ARC4_C:POLARSSL_SHA1_C:POLARSSL_PEM_C:POLARSSL_FS_IO
+x509parse_keyfile:"data_files/pkcs8_pbe_sha1_rc4_128.key":"PolarSSLTest":0
+
 X509 Parse Public Key #1 (PKCS#8 wrapped)
 depends_on:POLARSSL_MD5_C:POLARSSL_PEM_C:POLARSSL_FS_IO
 x509parse_public_keyfile:"data_files/format_gen.pub":0