constants.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
  2. /* SPDX-License-Identifier: Unlicense */
  3. #include "tomcrypt.h"
  4. #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L
  5. #include <libgen.h>
  6. #else
  7. #define basename(x) x
  8. #endif
  9. /**
  10. @file demo_crypt_constants.c
  11. Demo how to get various constants to dynamic languages
  12. like Python
  13. Larry Bugbee, February 2013
  14. */
  15. static void s_print_line(const char* cmd, const char* desc)
  16. {
  17. printf(" %-16s - %s\n", cmd, desc);
  18. }
  19. int main(int argc, char **argv)
  20. {
  21. if (argc == 1) {
  22. /* given a specific constant name, get and print its value */
  23. char name[] = "CTR_COUNTER_BIG_ENDIAN";
  24. int value;
  25. char *names_list;
  26. unsigned int names_list_len;
  27. if (crypt_get_constant(name, &value) != 0) exit(EXIT_FAILURE);
  28. printf("\n %s is %d \n\n", name, value);
  29. /* get and print the length of the names (and values) list */
  30. if (crypt_list_all_constants(NULL, &names_list_len) != 0) exit(EXIT_FAILURE);
  31. printf(" need to allocate %u bytes \n\n", names_list_len);
  32. /* get and print the names (and values) list */
  33. if ((names_list = malloc(names_list_len)) == NULL) exit(EXIT_FAILURE);
  34. if (crypt_list_all_constants(names_list, &names_list_len) != 0) exit(EXIT_FAILURE);
  35. printf(" supported constants:\n\n%s\n\n", names_list);
  36. free(names_list);
  37. } else if (argc == 2) {
  38. if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
  39. char* base = strdup(basename(argv[0]));
  40. printf("Usage: %s [-a] [-s name]\n\n", base);
  41. s_print_line("<no argument>", "The old behavior of the demo");
  42. s_print_line("-a", "Only lists all constants");
  43. s_print_line("-s name", "List a single constant given as argument");
  44. s_print_line("-h", "The help you're looking at");
  45. free(base);
  46. } else if (strcmp(argv[1], "-a") == 0) {
  47. char *names_list;
  48. unsigned int names_list_len;
  49. /* get and print the length of the names (and values) list */
  50. if (crypt_list_all_constants(NULL, &names_list_len) != 0) exit(EXIT_FAILURE);
  51. /* get and print the names (and values) list */
  52. if ((names_list = malloc(names_list_len)) == NULL) exit(EXIT_FAILURE);
  53. if (crypt_list_all_constants(names_list, &names_list_len) != 0) exit(EXIT_FAILURE);
  54. printf("%s\n", names_list);
  55. free(names_list);
  56. }
  57. } else if (argc == 3) {
  58. if (strcmp(argv[1], "-s") == 0) {
  59. int value;
  60. if (crypt_get_constant(argv[2], &value) != 0) exit(EXIT_FAILURE);
  61. printf("%s,%u\n", argv[2], value);
  62. }
  63. }
  64. return 0;
  65. }