sha_common.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Cryptographic API.
  4. *
  5. * s390 generic implementation of the SHA Secure Hash Algorithms.
  6. *
  7. * Copyright IBM Corp. 2007
  8. * Author(s): Jan Glauber (jang@de.ibm.com)
  9. */
  10. #include <crypto/internal/hash.h>
  11. #include <linux/module.h>
  12. #include <asm/cpacf.h>
  13. #include "sha.h"
  14. int s390_sha_update(struct shash_desc *desc, const u8 *data, unsigned int len)
  15. {
  16. struct s390_sha_ctx *ctx = shash_desc_ctx(desc);
  17. unsigned int bsize = crypto_shash_blocksize(desc->tfm);
  18. unsigned int index, n;
  19. /* how much is already in the buffer? */
  20. index = ctx->count & (bsize - 1);
  21. ctx->count += len;
  22. if ((index + len) < bsize)
  23. goto store;
  24. /* process one stored block */
  25. if (index) {
  26. memcpy(ctx->buf + index, data, bsize - index);
  27. cpacf_kimd(ctx->func, ctx->state, ctx->buf, bsize);
  28. data += bsize - index;
  29. len -= bsize - index;
  30. index = 0;
  31. }
  32. /* process as many blocks as possible */
  33. if (len >= bsize) {
  34. n = len & ~(bsize - 1);
  35. cpacf_kimd(ctx->func, ctx->state, data, n);
  36. data += n;
  37. len -= n;
  38. }
  39. store:
  40. if (len)
  41. memcpy(ctx->buf + index , data, len);
  42. return 0;
  43. }
  44. EXPORT_SYMBOL_GPL(s390_sha_update);
  45. int s390_sha_final(struct shash_desc *desc, u8 *out)
  46. {
  47. struct s390_sha_ctx *ctx = shash_desc_ctx(desc);
  48. unsigned int bsize = crypto_shash_blocksize(desc->tfm);
  49. u64 bits;
  50. unsigned int index, end, plen;
  51. /* SHA-512 uses 128 bit padding length */
  52. plen = (bsize > SHA256_BLOCK_SIZE) ? 16 : 8;
  53. /* must perform manual padding */
  54. index = ctx->count & (bsize - 1);
  55. end = (index < bsize - plen) ? bsize : (2 * bsize);
  56. /* start pad with 1 */
  57. ctx->buf[index] = 0x80;
  58. index++;
  59. /* pad with zeros */
  60. memset(ctx->buf + index, 0x00, end - index - 8);
  61. /*
  62. * Append message length. Well, SHA-512 wants a 128 bit length value,
  63. * nevertheless we use u64, should be enough for now...
  64. */
  65. bits = ctx->count * 8;
  66. memcpy(ctx->buf + end - 8, &bits, sizeof(bits));
  67. cpacf_kimd(ctx->func, ctx->state, ctx->buf, end);
  68. /* copy digest to out */
  69. memcpy(out, ctx->state, crypto_shash_digestsize(desc->tfm));
  70. /* wipe context */
  71. memset(ctx, 0, sizeof *ctx);
  72. return 0;
  73. }
  74. EXPORT_SYMBOL_GPL(s390_sha_final);
  75. MODULE_LICENSE("GPL");
  76. MODULE_DESCRIPTION("s390 SHA cipher common functions");