2
0

p5_pbe.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  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
  8. */
  9. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/asn1t.h>
  12. #include <openssl/x509.h>
  13. #include <openssl/rand.h>
  14. /* PKCS#5 password based encryption structure */
  15. ASN1_SEQUENCE(PBEPARAM) = {
  16. ASN1_SIMPLE(PBEPARAM, salt, ASN1_OCTET_STRING),
  17. ASN1_SIMPLE(PBEPARAM, iter, ASN1_INTEGER)
  18. } ASN1_SEQUENCE_END(PBEPARAM)
  19. IMPLEMENT_ASN1_FUNCTIONS(PBEPARAM)
  20. /* Set an algorithm identifier for a PKCS#5 PBE algorithm */
  21. int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
  22. const unsigned char *salt, int saltlen)
  23. {
  24. PBEPARAM *pbe = NULL;
  25. ASN1_STRING *pbe_str = NULL;
  26. unsigned char *sstr = NULL;
  27. pbe = PBEPARAM_new();
  28. if (pbe == NULL) {
  29. ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
  30. goto err;
  31. }
  32. if (iter <= 0)
  33. iter = PKCS5_DEFAULT_ITER;
  34. if (!ASN1_INTEGER_set(pbe->iter, iter)) {
  35. ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
  36. goto err;
  37. }
  38. if (!saltlen)
  39. saltlen = PKCS5_SALT_LEN;
  40. sstr = OPENSSL_malloc(saltlen);
  41. if (sstr == NULL) {
  42. ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
  43. goto err;
  44. }
  45. if (salt)
  46. memcpy(sstr, salt, saltlen);
  47. else if (RAND_bytes(sstr, saltlen) <= 0)
  48. goto err;
  49. ASN1_STRING_set0(pbe->salt, sstr, saltlen);
  50. sstr = NULL;
  51. if (!ASN1_item_pack(pbe, ASN1_ITEM_rptr(PBEPARAM), &pbe_str)) {
  52. ASN1err(ASN1_F_PKCS5_PBE_SET0_ALGOR, ERR_R_MALLOC_FAILURE);
  53. goto err;
  54. }
  55. PBEPARAM_free(pbe);
  56. pbe = NULL;
  57. if (X509_ALGOR_set0(algor, OBJ_nid2obj(alg), V_ASN1_SEQUENCE, pbe_str))
  58. return 1;
  59. err:
  60. OPENSSL_free(sstr);
  61. PBEPARAM_free(pbe);
  62. ASN1_STRING_free(pbe_str);
  63. return 0;
  64. }
  65. /* Return an algorithm identifier for a PKCS#5 PBE algorithm */
  66. X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
  67. const unsigned char *salt, int saltlen)
  68. {
  69. X509_ALGOR *ret;
  70. ret = X509_ALGOR_new();
  71. if (ret == NULL) {
  72. ASN1err(ASN1_F_PKCS5_PBE_SET, ERR_R_MALLOC_FAILURE);
  73. return NULL;
  74. }
  75. if (PKCS5_pbe_set0_algor(ret, alg, iter, salt, saltlen))
  76. return ret;
  77. X509_ALGOR_free(ret);
  78. return NULL;
  79. }