p5_pbe.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 1999-2021 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/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. ERR_raise(ERR_LIB_ASN1, 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. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  36. goto err;
  37. }
  38. if (!saltlen)
  39. saltlen = PKCS5_SALT_LEN;
  40. if (saltlen < 0)
  41. goto err;
  42. sstr = OPENSSL_malloc(saltlen);
  43. if (sstr == NULL) {
  44. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  45. goto err;
  46. }
  47. if (salt)
  48. memcpy(sstr, salt, saltlen);
  49. else if (RAND_bytes(sstr, saltlen) <= 0)
  50. goto err;
  51. ASN1_STRING_set0(pbe->salt, sstr, saltlen);
  52. sstr = NULL;
  53. if (!ASN1_item_pack(pbe, ASN1_ITEM_rptr(PBEPARAM), &pbe_str)) {
  54. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  55. goto err;
  56. }
  57. PBEPARAM_free(pbe);
  58. pbe = NULL;
  59. if (X509_ALGOR_set0(algor, OBJ_nid2obj(alg), V_ASN1_SEQUENCE, pbe_str))
  60. return 1;
  61. err:
  62. OPENSSL_free(sstr);
  63. PBEPARAM_free(pbe);
  64. ASN1_STRING_free(pbe_str);
  65. return 0;
  66. }
  67. /* Return an algorithm identifier for a PKCS#5 PBE algorithm */
  68. X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
  69. const unsigned char *salt, int saltlen)
  70. {
  71. X509_ALGOR *ret;
  72. ret = X509_ALGOR_new();
  73. if (ret == NULL) {
  74. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  75. return NULL;
  76. }
  77. if (PKCS5_pbe_set0_algor(ret, alg, iter, salt, saltlen))
  78. return ret;
  79. X509_ALGOR_free(ret);
  80. return NULL;
  81. }