tss2_decrypt.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 command line parameters */
  7. static struct cxt {
  8. char const *keyPath;
  9. char const *plainText;
  10. char const *cipherText;
  11. bool overwrite;
  12. } ctx;
  13. /* Parse command line parameters */
  14. static bool on_option(char key, char *value) {
  15. switch (key) {
  16. case 'i':
  17. ctx.cipherText = value;
  18. break;
  19. case 'f':
  20. ctx.overwrite = true;
  21. break;
  22. case 'o':
  23. ctx.plainText = value;
  24. break;
  25. case 'p':
  26. ctx.keyPath = value;
  27. break;
  28. }
  29. return true;
  30. }
  31. /* Define possible command line parameters */
  32. static bool tss2_tool_onstart(tpm2_options **opts) {
  33. struct option topts[] = {
  34. {"keyPath", required_argument, NULL, 'p'},
  35. {"cipherText", required_argument, NULL, 'i'},
  36. {"force" , no_argument , NULL, 'f'},
  37. {"plainText" , required_argument, NULL, 'o'},
  38. };
  39. return (*opts = tpm2_options_new ("i:fo:p:", 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.cipherText) {
  50. fprintf (stderr, "No encrypted text provided, use --cipherText\n");
  51. return -1;
  52. }
  53. if (!ctx.plainText) {
  54. fprintf (stderr, "No output file provided, use --plainText\n");
  55. return -1;
  56. }
  57. /* Read ciphertext file */
  58. uint8_t* cipherText;
  59. size_t cipherTextSize;
  60. TSS2_RC r = open_read_and_close (ctx.cipherText, (void**)&cipherText,
  61. &cipherTextSize);
  62. if (r){
  63. return 1;
  64. }
  65. /* Execute FAPI command with passed arguments */
  66. uint8_t *plainText;
  67. size_t plainTextSize;
  68. r = Fapi_Decrypt (fctx, ctx.keyPath, cipherText, cipherTextSize,
  69. &plainText, &plainTextSize);
  70. if (r != TSS2_RC_SUCCESS) {
  71. free(cipherText);
  72. LOG_PERR ("Fapi_Decrypt", r);
  73. return 1;
  74. }
  75. free(cipherText);
  76. /* Write returned data to file(s) */
  77. r = open_write_and_close (ctx.plainText, ctx.overwrite, plainText,
  78. plainTextSize);
  79. if (r){
  80. Fapi_Free (plainText);
  81. return 1;
  82. }
  83. Fapi_Free (plainText);
  84. return 0;
  85. }
  86. TSS2_TOOL_REGISTER("decrypt", tss2_tool_onstart, tss2_tool_onrun, NULL)