2 * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "internal/cryptlib.h"
12 #include <openssl/pkcs12.h>
14 /* Define this to dump decrypted output to files called DERnnn */
16 * #define OPENSSL_DEBUG_DECRYPT
20 * Encrypt/Decrypt a buffer based on password and algor, result in a
21 * OPENSSL_malloc'ed buffer
23 unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor,
24 const char *pass, int passlen,
25 const unsigned char *in, int inlen,
26 unsigned char **data, int *datalen, int en_de)
28 unsigned char *out = NULL;
30 EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
33 PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_MALLOC_FAILURE);
38 if (!EVP_PBE_CipherInit(algor->algorithm, pass, passlen,
39 algor->parameter, ctx, en_de)) {
40 PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT,
41 PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR);
45 if ((out = OPENSSL_malloc(inlen + EVP_CIPHER_CTX_block_size(ctx)))
47 PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_MALLOC_FAILURE);
51 if (!EVP_CipherUpdate(ctx, out, &i, in, inlen)) {
54 PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_EVP_LIB);
59 if (!EVP_CipherFinal_ex(ctx, out + i, &i)) {
62 PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT,
63 PKCS12_R_PKCS12_CIPHERFINAL_ERROR);
72 EVP_CIPHER_CTX_free(ctx);
78 * Decrypt an OCTET STRING and decode ASN1 structure if zbuf set zero buffer
82 void *PKCS12_item_decrypt_d2i(const X509_ALGOR *algor, const ASN1_ITEM *it,
83 const char *pass, int passlen,
84 const ASN1_OCTET_STRING *oct, int zbuf)
87 const unsigned char *p;
91 if (!PKCS12_pbe_crypt(algor, pass, passlen, oct->data, oct->length,
93 PKCS12err(PKCS12_F_PKCS12_ITEM_DECRYPT_D2I,
94 PKCS12_R_PKCS12_PBE_CRYPT_ERROR);
98 #ifdef OPENSSL_DEBUG_DECRYPT
104 sprintf(fname, "DER%d", fnm++);
105 op = fopen(fname, "wb");
106 fwrite(p, 1, outlen, op);
110 ret = ASN1_item_d2i(NULL, &p, outlen, it);
112 OPENSSL_cleanse(out, outlen);
114 PKCS12err(PKCS12_F_PKCS12_ITEM_DECRYPT_D2I, PKCS12_R_DECODE_ERROR);
120 * Encode ASN1 structure and encrypt, return OCTET STRING if zbuf set zero
124 ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor,
126 const char *pass, int passlen,
129 ASN1_OCTET_STRING *oct = NULL;
130 unsigned char *in = NULL;
133 if ((oct = ASN1_OCTET_STRING_new()) == NULL) {
134 PKCS12err(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, ERR_R_MALLOC_FAILURE);
137 inlen = ASN1_item_i2d(obj, &in, it);
139 PKCS12err(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, PKCS12_R_ENCODE_ERROR);
142 if (!PKCS12_pbe_crypt(algor, pass, passlen, in, inlen, &oct->data,
144 PKCS12err(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, PKCS12_R_ENCRYPT_ERROR);
149 OPENSSL_cleanse(in, inlen);
153 ASN1_OCTET_STRING_free(oct);