cryptosha256.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * cryptosha256.c
  3. */
  4. #include <crypto/internal/hash.h>
  5. #include <linux/module.h>
  6. #define SHA256_LENGTH 32
  7. static void show_hash_result(char *plaintext, char *hash_sha256)
  8. {
  9. int i;
  10. char str[SHA256_LENGTH * 2 + 1];
  11. pr_info("sha256 test for string: \"%s\"\n", plaintext);
  12. for (i = 0; i < SHA256_LENGTH; i++)
  13. sprintf(&str[i * 2], "%02x", (unsigned char)hash_sha256[i]);
  14. str[i * 2] = 0;
  15. pr_info("%s\n", str);
  16. }
  17. static int __init cryptosha256_init(void)
  18. {
  19. char *plaintext = "This is a test";
  20. char hash_sha256[SHA256_LENGTH];
  21. struct crypto_shash *sha256;
  22. struct shash_desc *shash;
  23. sha256 = crypto_alloc_shash("sha256", 0, 0);
  24. if (IS_ERR(sha256)) {
  25. pr_err(
  26. "%s(): Failed to allocate sha256 algorithm, enable CONFIG_CRYPTO_SHA256 and try again.\n",
  27. __func__);
  28. return -1;
  29. }
  30. shash = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(sha256),
  31. GFP_KERNEL);
  32. if (!shash)
  33. return -ENOMEM;
  34. shash->tfm = sha256;
  35. if (crypto_shash_init(shash))
  36. return -1;
  37. if (crypto_shash_update(shash, plaintext, strlen(plaintext)))
  38. return -1;
  39. if (crypto_shash_final(shash, hash_sha256))
  40. return -1;
  41. kfree(shash);
  42. crypto_free_shash(sha256);
  43. show_hash_result(plaintext, hash_sha256);
  44. return 0;
  45. }
  46. static void __exit cryptosha256_exit(void)
  47. {
  48. }
  49. module_init(cryptosha256_init);
  50. module_exit(cryptosha256_exit);
  51. MODULE_DESCRIPTION("sha256 hash test");
  52. MODULE_LICENSE("GPL");