tss2_encrypt.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include <stdbool.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include "tools/fapi/tss2_template.h"
  6. /* Context struct used to store passed commandline parameters */
  7. static struct cxt {
  8. char const *keyPath;
  9. char const *plainText;
  10. char const *cipherText;
  11. bool overwrite;
  12. } ctx;
  13. /* Parse commandline parameters */
  14. static bool on_option(char key, char *value) {
  15. switch (key) {
  16. case 'f':
  17. ctx.overwrite = true;
  18. break;
  19. case 'o':
  20. ctx.cipherText = value;
  21. break;
  22. case 'p':
  23. ctx.keyPath = value;
  24. break;
  25. case 'i':
  26. ctx.plainText = value;
  27. break;
  28. }
  29. return true;
  30. }
  31. /* Define possible commandline parameters */
  32. static bool tss2_tool_onstart(tpm2_options **opts) {
  33. struct option topts[] = {
  34. {"keyPath", required_argument, NULL, 'p'},
  35. {"plainText", required_argument, NULL, 'i'},
  36. {"cipherText", required_argument, NULL, 'o'},
  37. {"force", no_argument , NULL, 'f'},
  38. };
  39. return (*opts = tpm2_options_new ("fo:p:i:", ARRAY_LEN(topts), topts,
  40. on_option, NULL, 0)) != NULL;
  41. }
  42. /* Execute specific tool */
  43. static int tss2_tool_onrun (FAPI_CONTEXT *fctx) {
  44. /* Check availability of required parameters */
  45. if (!ctx.keyPath) {
  46. fprintf (stderr, "No key path provided, use --keyPath\n");
  47. return -1;
  48. }
  49. if (!ctx.plainText) {
  50. fprintf (stderr, "No text to encrypt provided, use --plainText\n");
  51. return -1;
  52. }
  53. if (!ctx.cipherText) {
  54. fprintf (stderr, "No output file provided, --cipherText\n");
  55. return -1;
  56. }
  57. /* Read plaintext file */
  58. uint8_t *plainText;
  59. size_t plainTextSize;
  60. TSS2_RC r = open_read_and_close (ctx.plainText, (void**)&plainText,
  61. &plainTextSize);
  62. if (r){
  63. return 1;
  64. }
  65. /* Execute FAPI command with passed arguments */
  66. uint8_t *cipherText;
  67. size_t cipherTextSize;
  68. r = Fapi_Encrypt (fctx, ctx.keyPath, plainText, plainTextSize,
  69. &cipherText, &cipherTextSize);
  70. if (r != TSS2_RC_SUCCESS) {
  71. LOG_PERR ("Fapi_Encrypt", r);
  72. free (plainText);
  73. return 1;
  74. }
  75. free (plainText);
  76. /* Write returned data to file(s) */
  77. r = open_write_and_close (ctx.cipherText, ctx.overwrite, cipherText,
  78. cipherTextSize);
  79. if (r) {
  80. Fapi_Free (cipherText);
  81. return 1;
  82. }
  83. Fapi_Free (cipherText);
  84. return 0;
  85. }
  86. TSS2_TOOL_REGISTER("encrypt", tss2_tool_onstart, tss2_tool_onrun, NULL)