2
0

p12_p8e.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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
  8. */
  9. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/pkcs12.h>
  12. #include "crypto/x509.h"
  13. X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher,
  14. const char *pass, int passlen,
  15. unsigned char *salt, int saltlen, int iter,
  16. PKCS8_PRIV_KEY_INFO *p8inf)
  17. {
  18. X509_SIG *p8 = NULL;
  19. X509_ALGOR *pbe;
  20. if (pbe_nid == -1)
  21. pbe = PKCS5_pbe2_set(cipher, iter, salt, saltlen);
  22. else if (EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0))
  23. pbe = PKCS5_pbe2_set_iv(cipher, iter, salt, saltlen, NULL, pbe_nid);
  24. else {
  25. ERR_clear_error();
  26. pbe = PKCS5_pbe_set(pbe_nid, iter, salt, saltlen);
  27. }
  28. if (pbe == NULL) {
  29. PKCS12err(PKCS12_F_PKCS8_ENCRYPT, ERR_R_ASN1_LIB);
  30. return NULL;
  31. }
  32. p8 = PKCS8_set0_pbe(pass, passlen, p8inf, pbe);
  33. if (p8 == NULL) {
  34. X509_ALGOR_free(pbe);
  35. return NULL;
  36. }
  37. return p8;
  38. }
  39. X509_SIG *PKCS8_set0_pbe(const char *pass, int passlen,
  40. PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe)
  41. {
  42. X509_SIG *p8;
  43. ASN1_OCTET_STRING *enckey;
  44. enckey =
  45. PKCS12_item_i2d_encrypt(pbe, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO),
  46. pass, passlen, p8inf, 1);
  47. if (!enckey) {
  48. PKCS12err(PKCS12_F_PKCS8_SET0_PBE, PKCS12_R_ENCRYPT_ERROR);
  49. return NULL;
  50. }
  51. p8 = OPENSSL_zalloc(sizeof(*p8));
  52. if (p8 == NULL) {
  53. PKCS12err(PKCS12_F_PKCS8_SET0_PBE, ERR_R_MALLOC_FAILURE);
  54. ASN1_OCTET_STRING_free(enckey);
  55. return NULL;
  56. }
  57. p8->algor = pbe;
  58. p8->digest = enckey;
  59. return p8;
  60. }