dsa_sign.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* dsa_sign.c */
  2. /*
  3. This file is part of the ARM-Crypto-Lib.
  4. Copyright (C) 2006-2010 Daniel Otte (daniel.otte@rub.de)
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include <stdint.h>
  17. #include <string.h>
  18. #include <crypto/bigint.h>
  19. #include <crypto/dsa.h>
  20. #include <crypto/hashfunction_descriptor.h>
  21. #include <crypto/hfal-basic.h>
  22. #define MAX(a,b) (((a)>(b))?(a):(b))
  23. uint8_t dsa_sign_bigint(dsa_signature_t* s, const bigint_t* m,
  24. const dsa_ctx_t* ctx, const bigint_t* k){
  25. bigint_t tmp, tmp2;
  26. bigint_word_t tmp_b[ctx->domain.p.length_W+5], tmp2_b[ctx->domain.q.length_W+5];
  27. tmp.wordv= tmp_b;
  28. tmp2.wordv = tmp2_b;
  29. bigint_expmod_u(&tmp, &(ctx->domain.g), k, &(ctx->domain.p));
  30. bigint_reduce(&tmp, &(ctx->domain.q));
  31. bigint_copy(&(s->r), &tmp);
  32. bigint_mul_u(&tmp, &tmp, &(ctx->priv));
  33. bigint_add_u(&tmp, &tmp, m);
  34. bigint_inverse(&tmp2, k, &(ctx->domain.q));
  35. bigint_mul_u(&tmp, &tmp, &tmp2);
  36. bigint_reduce(&tmp, &(ctx->domain.q));
  37. bigint_copy(&(s->s), &tmp);
  38. if(s->s.length_W==0 || s->r.length_W==0){
  39. return 1;
  40. }
  41. return 0;
  42. }
  43. uint8_t dsa_sign_message(dsa_signature_t* s, const void* m, uint16_t m_len_b,
  44. const hfdesc_t* hash_desc, const dsa_ctx_t* ctx,
  45. uint8_t(*rand_in)(void)){
  46. bigint_t z, k;
  47. uint16_t i, n_B = ctx->domain.q.length_W;
  48. unsigned hash_length = MAX(n_B,(hfal_hash_getHashsize(hash_desc)+sizeof(bigint_word_t)*8-1)/(sizeof(bigint_word_t)*8));
  49. bigint_word_t hash_value[hash_length];
  50. bigint_word_t k_b[n_B];
  51. memset(hash_value, 0, hash_length*sizeof(bigint_word_t));
  52. hfal_hash_mem(hash_desc, hash_value, m, m_len_b);
  53. z.wordv = hash_value;
  54. z.length_W = n_B;
  55. bigint_changeendianess(&z);
  56. k.wordv = k_b;
  57. k.length_W = n_B;
  58. do{
  59. for(i=0; i<n_B*sizeof(bigint_word_t); ++i){
  60. ((uint8_t*)k_b)[i] = rand_in();
  61. }
  62. k.length_W = n_B;
  63. bigint_adjust(&k);
  64. }while(dsa_sign_bigint(s, &z, ctx, &k));
  65. return 0;
  66. }