| 1 |
// Copyright (C) 1995-1998 Eric Young ([email protected]) All rights reserved. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
#include <openssl/asn1.h> |
| 5 |
#include <openssl/digest.h> |
| 6 |
#include <openssl/err.h> |
| 7 |
#include <openssl/evp.h> |
| 8 |
#include <openssl/mem.h> |
| 9 |
#include <openssl/obj.h> |
| 10 |
#include <openssl/x509.h> |
| 11 |
|
| 12 |
#include <limits.h> |
| 13 |
|
| 14 |
#include "internal.h" |
| 15 |
|
| 16 |
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, |
| 17 |
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey, |
| 18 |
const EVP_MD *type) { |
| 19 |
if (signature->type != V_ASN1_BIT_STRING) { |
| 20 |
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); |
| 21 |
return 0; |
| 22 |
} |
| 23 |
EVP_MD_CTX ctx; |
| 24 |
EVP_MD_CTX_init(&ctx); |
| 25 |
if (!EVP_DigestSignInit(&ctx, NULL, type, NULL, pkey)) { |
| 26 |
EVP_MD_CTX_cleanup(&ctx); |
| 27 |
return 0; |
| 28 |
} |
| 29 |
return ASN1_item_sign_ctx(it, algor1, algor2, signature, asn, &ctx); |
| 30 |
} |
| 31 |
|
| 32 |
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1, |
| 33 |
X509_ALGOR *algor2, ASN1_BIT_STRING *signature, |
| 34 |
void *asn, EVP_MD_CTX *ctx) { |
| 35 |
int ret = 0; |
| 36 |
uint8_t *in = NULL, *out = NULL; |
| 37 |
if (signature->type != V_ASN1_BIT_STRING) { |
| 38 |
OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE); |
| 39 |
goto err; |
| 40 |
} |
| 41 |
|
| 42 |
// Write out the requested copies of the AlgorithmIdentifier. |
| 43 |
if (algor1 && !x509_digest_sign_algorithm(ctx, algor1)) { |
| 44 |
goto err; |
| 45 |
} |
| 46 |
if (algor2 && !x509_digest_sign_algorithm(ctx, algor2)) { |
| 47 |
goto err; |
| 48 |
} |
| 49 |
|
| 50 |
int in_len = ASN1_item_i2d(asn, &in, it); |
| 51 |
if (in_len < 0) { |
| 52 |
goto err; |
| 53 |
} |
| 54 |
|
| 55 |
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx->pctx); |
| 56 |
size_t out_len = EVP_PKEY_size(pkey); |
| 57 |
if (out_len > INT_MAX) { |
| 58 |
OPENSSL_PUT_ERROR(X509, ERR_R_OVERFLOW); |
| 59 |
goto err; |
| 60 |
} |
| 61 |
|
| 62 |
out = OPENSSL_malloc(out_len); |
| 63 |
if (out == NULL) { |
| 64 |
goto err; |
| 65 |
} |
| 66 |
|
| 67 |
if (!EVP_DigestSign(ctx, out, &out_len, in, in_len)) { |
| 68 |
OPENSSL_PUT_ERROR(X509, ERR_R_EVP_LIB); |
| 69 |
goto err; |
| 70 |
} |
| 71 |
|
| 72 |
ASN1_STRING_set0(signature, out, (int)out_len); |
| 73 |
out = NULL; |
| 74 |
signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); |
| 75 |
signature->flags |= ASN1_STRING_FLAG_BITS_LEFT; |
| 76 |
ret = (int)out_len; |
| 77 |
|
| 78 |
err: |
| 79 |
EVP_MD_CTX_cleanup(ctx); |
| 80 |
OPENSSL_free(in); |
| 81 |
OPENSSL_free(out); |
| 82 |
return ret; |
| 83 |
} |