cryptosha256.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. int 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. return -1;
  26. shash = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(sha256),
  27. GFP_KERNEL);
  28. if (!shash)
  29. return -ENOMEM;
  30. shash->tfm = sha256;
  31. if (crypto_shash_init(shash))
  32. return -1;
  33. if (crypto_shash_update(shash, plaintext, strlen(plaintext)))
  34. return -1;
  35. if (crypto_shash_final(shash, hash_sha256))
  36. return -1;
  37. kfree(shash);
  38. crypto_free_shash(sha256);
  39. show_hash_result(plaintext, hash_sha256);
  40. return 0;
  41. }
  42. void cryptosha256_exit(void) {}
  43. module_init(cryptosha256_init);
  44. module_exit(cryptosha256_exit);
  45. MODULE_DESCRIPTION("sha256 hash test");
  46. MODULE_LICENSE("GPL");