#include "common.h"
#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
#include "mbedtls/pem.h"
#include "mbedtls/base64.h"
#include "mbedtls/des.h"
#include "mbedtls/aes.h"
#include "mbedtls/md.h"
#include "mbedtls/cipher.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#include "mbedtls/platform.h"
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#include "psa/crypto.h"
#endif
#if defined(MBEDTLS_MD_CAN_MD5) && \
defined(MBEDTLS_CIPHER_MODE_CBC) && \
(defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C))
#define PEM_RFC1421
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
void mbedtls_pem_init(mbedtls_pem_context *ctx)
{ … }
#if defined(PEM_RFC1421)
static int pem_get_iv(const unsigned char *s, unsigned char *iv,
size_t iv_len)
{ … }
static int pem_pbkdf1(unsigned char *key, size_t keylen,
unsigned char *iv,
const unsigned char *pwd, size_t pwdlen)
{ … }
#if defined(MBEDTLS_DES_C)
static int pem_des_decrypt(unsigned char des_iv[8],
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen)
{
mbedtls_des_context des_ctx;
unsigned char des_key[8];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_des_init(&des_ctx);
if ((ret = pem_pbkdf1(des_key, 8, des_iv, pwd, pwdlen)) != 0) {
goto exit;
}
if ((ret = mbedtls_des_setkey_dec(&des_ctx, des_key)) != 0) {
goto exit;
}
ret = mbedtls_des_crypt_cbc(&des_ctx, MBEDTLS_DES_DECRYPT, buflen,
des_iv, buf, buf);
exit:
mbedtls_des_free(&des_ctx);
mbedtls_platform_zeroize(des_key, 8);
return ret;
}
static int pem_des3_decrypt(unsigned char des3_iv[8],
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen)
{
mbedtls_des3_context des3_ctx;
unsigned char des3_key[24];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_des3_init(&des3_ctx);
if ((ret = pem_pbkdf1(des3_key, 24, des3_iv, pwd, pwdlen)) != 0) {
goto exit;
}
if ((ret = mbedtls_des3_set3key_dec(&des3_ctx, des3_key)) != 0) {
goto exit;
}
ret = mbedtls_des3_crypt_cbc(&des3_ctx, MBEDTLS_DES_DECRYPT, buflen,
des3_iv, buf, buf);
exit:
mbedtls_des3_free(&des3_ctx);
mbedtls_platform_zeroize(des3_key, 24);
return ret;
}
#endif
#if defined(MBEDTLS_AES_C)
static int pem_aes_decrypt(unsigned char aes_iv[16], unsigned int keylen,
unsigned char *buf, size_t buflen,
const unsigned char *pwd, size_t pwdlen)
{ … }
#endif
#if defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C)
static int pem_check_pkcs_padding(unsigned char *input, size_t input_len, size_t *data_len)
{ … }
#endif
#endif
int mbedtls_pem_read_buffer(mbedtls_pem_context *ctx, const char *header, const char *footer,
const unsigned char *data, const unsigned char *pwd,
size_t pwdlen, size_t *use_len)
{ … }
void mbedtls_pem_free(mbedtls_pem_context *ctx)
{ … }
#endif
#if defined(MBEDTLS_PEM_WRITE_C)
int mbedtls_pem_write_buffer(const char *header, const char *footer,
const unsigned char *der_data, size_t der_len,
unsigned char *buf, size_t buf_len, size_t *olen)
{ … }
#endif
#endif