3 This file is part of the ARM-Crypto-Lib.
4 Copyright (C) 2006-2011 Daniel Otte (daniel.otte@rub.de)
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "rsa_basic.h"
28 void rsa_enc(bigint_t* data, rsa_publickey_t* key){
29 bigint_expmod_u(data, data, key->exponent, key->modulus);
36 h = (m1 - m2) * qinv % p
40 uint8_t rsa_dec_crt_mono(bigint_t* data, rsa_privatekey_t* key){
42 m1.wordv = malloc(key->components[0]->length_B * sizeof(bigint_word_t));
43 m2.wordv = malloc(key->components[1]->length_B * sizeof(bigint_word_t));
44 if(!m1.wordv || !m2.wordv){
49 bigint_expmod_u(&m1, data, key->components[2], key->components[0]);
50 bigint_expmod_u(&m2, data, key->components[3], key->components[1]);
51 bigint_sub_s(&m1, &m1, &m2);
52 while(BIGINT_NEG_MASK & m1.info){
53 bigint_add_s(&m1, &m1, key->components[0]);
55 bigint_reduce(&m1, key->components[0]);
56 bigint_mul_u(data, &m1, key->components[4]);
57 bigint_reduce(data, key->components[0]);
58 bigint_mul_u(data, data, key->components[1]);
59 bigint_add_u(data, data, &m2);
65 uint8_t rsa_dec(bigint_t* data, rsa_privatekey_t* key){
67 bigint_expmod_u(data, data, key->components[0], key->modulus);
71 if (rsa_dec_crt_mono(data, key)){
76 if(key->n<8 || (key->n-5)%3 != 0){
79 //rsa_dec_crt_multi(data, key, (key->n-5)/3);
83 void rsa_os2ip(bigint_t* dest, const void* data, uint32_t length_B){
85 off = length_B % sizeof(bigint_word_t);
88 dest->wordv = realloc(dest->wordv, length_B + sizeof(bigint_word_t) - off);
89 memmove((uint8_t*)dest->wordv+off, dest->wordv, length_B);
90 memset(dest->wordv, 0, off);
94 memcpy((uint8_t*)dest->wordv + off, data, length_B);
97 memcpy(dest->wordv, data, length_B);
100 dest->length_B = (length_B + sizeof(bigint_word_t) - 1) / sizeof(bigint_word_t);
101 bigint_changeendianess(dest);
105 void rsa_i2osp(void* dest, bigint_t* src, uint16_t* out_length_B){
106 *out_length_B = bigint_get_first_set_bit(src) / 8 + 1;
109 for(i=*out_length_B; i>0; --i){
110 *((uint8_t*)dest) = ((uint8_t*)src->wordv)[i-1];
111 dest = (uint8_t*)dest + 1;
115 bigint_changeendianess(src);
118 off = bigint_get_last_set_bit(src)/8;
120 memmove(src->wordv, (uint8_t*)src->wordv+off, *out_length_B);