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"
26 #include "bigint_io.h"
29 #include "random_dummy.h"
31 uint8_t rsa_encrypt_pkcs15(void* dest, uint16_t* out_length, const void* src,
32 uint16_t length_B, rsa_publickey_t* key, const void* pad){
35 pad_length = (bigint_get_first_set_bit(key->modulus) + 7) / 8 - length_B - 3;
37 cli_putstr("\r\nERROR: pad_length<8; pad_length: ");
38 cli_hexdump_rev(&pad_length, 2);
39 return 2; /* message to long */
44 for(i=0; i<pad_length; ++i){
48 ((uint8_t*)dest)[i+2] = c;
51 memcpy((uint8_t*)dest + 2, pad, pad_length);
53 ((uint8_t*)dest)[0] = 0x00;
54 ((uint8_t*)dest)[1] = 0x02;
55 ((uint8_t*)dest)[2+pad_length] = 0x00;
56 memcpy((uint8_t*)dest+3+pad_length, src, length_B);
58 x.length_B = (length_B+pad_length+3+sizeof(bigint_word_t)-1)/sizeof(bigint_word_t);
60 rsa_os2ip(&x, NULL, length_B+pad_length+3);
62 rsa_i2osp(NULL, &x, out_length);
66 uint8_t rsa_decrypt_pkcs15(void* dest, uint16_t* out_length, const void* src,
67 uint16_t length_B, rsa_privatekey_t* key, void* pad){
69 uint16_t m_length, pad_length=0, idx=0;
71 rsa_os2ip(&x, src, length_B);
73 rsa_i2osp(NULL, &x, &m_length);
74 while(((uint8_t*)x.wordv)[idx]==0 && idx<m_length){
77 if(((uint8_t*)x.wordv)[idx]!=2 || idx>=m_length){
81 while(((uint8_t*)x.wordv)[idx+pad_length]!=0 && (idx+pad_length)<m_length){
84 if(pad_length<8 || (idx+pad_length)>=m_length){
87 *out_length = m_length - idx - pad_length - 1;
88 memcpy(dest, ((uint8_t*)x.wordv) + idx + pad_length + 1, m_length - idx - pad_length - 1);
90 memcpy(pad, ((uint8_t*)x.wordv)+idx, pad_length);