crypto_wrapper.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <furi_hal.h>
  2. #include "crypto/gcm.h"
  3. #include "crypto_wrapper.h"
  4. struct ESugGhzChatCryptoCtx {
  5. gcm_context gcm_ctx;
  6. };
  7. void crypto_init(void)
  8. {
  9. /* init the GCM and AES tables */
  10. gcm_initialize();
  11. }
  12. void crypto_explicit_bzero(void *s, size_t len)
  13. {
  14. memset(s, 0, len);
  15. asm volatile("" ::: "memory");
  16. }
  17. ESubGhzChatCryptoCtx *crypto_ctx_alloc(void)
  18. {
  19. ESubGhzChatCryptoCtx *ret = malloc(sizeof(ESubGhzChatCryptoCtx));
  20. if (ret != NULL) {
  21. memset(ret, 0, sizeof(ESubGhzChatCryptoCtx));
  22. }
  23. return ret;
  24. }
  25. void crypto_ctx_free(ESubGhzChatCryptoCtx *ctx)
  26. {
  27. crypto_ctx_clear(ctx);
  28. free(ctx);
  29. }
  30. void crypto_ctx_clear(ESubGhzChatCryptoCtx *ctx)
  31. {
  32. crypto_explicit_bzero(ctx, sizeof(ESubGhzChatCryptoCtx));
  33. }
  34. bool crypto_ctx_set_key(ESubGhzChatCryptoCtx *ctx, const uint8_t *key)
  35. {
  36. return (gcm_setkey(&(ctx->gcm_ctx), key, KEY_BITS / 8) == 0);
  37. }
  38. bool crypto_ctx_decrypt(ESubGhzChatCryptoCtx *ctx, uint8_t *in, size_t in_len,
  39. uint8_t *out)
  40. {
  41. if (in_len < MSG_OVERHEAD + 1) {
  42. return false;
  43. }
  44. return (gcm_auth_decrypt(&(ctx->gcm_ctx),
  45. in, IV_BYTES,
  46. NULL, 0,
  47. in + IV_BYTES, out, in_len - MSG_OVERHEAD,
  48. in + in_len - TAG_BYTES, TAG_BYTES) == 0);
  49. }
  50. bool crypto_ctx_encrypt(ESubGhzChatCryptoCtx *ctx, uint8_t *in, size_t in_len,
  51. uint8_t *out)
  52. {
  53. furi_hal_random_fill_buf(out, IV_BYTES);
  54. return (gcm_crypt_and_tag(&(ctx->gcm_ctx), ENCRYPT,
  55. out, IV_BYTES,
  56. NULL, 0,
  57. in, out + IV_BYTES, in_len,
  58. out + IV_BYTES + in_len, TAG_BYTES) == 0);
  59. }