cryptosha256.c 1.3 KB

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