Revert "Merge branch 'upstream' into tizen"
[platform/upstream/nettle.git] / pkcs1-decrypt.c
1 /* pkcs1-decrypt.c
2  *
3  */
4
5 /* nettle, low-level cryptographics library
6  *
7  * Copyright (C) 2001, 2012 Niels Möller
8  *  
9  * The nettle library is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or (at your
12  * option) any later version.
13  * 
14  * The nettle library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17  * License for more details.
18  * 
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with the nettle library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22  * MA 02111-1301, USA.
23  */
24
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <string.h>
30
31 #include "pkcs1.h"
32
33 #include "bignum.h"
34 #include "nettle-internal.h"
35
36 int
37 pkcs1_decrypt (unsigned key_size,
38                const mpz_t m,
39                unsigned *length, uint8_t *message)
40 {
41   TMP_DECL(em, uint8_t, NETTLE_MAX_BIGNUM_SIZE);
42   uint8_t *terminator;
43   unsigned padding;
44   unsigned message_length;
45
46   TMP_ALLOC(em, key_size);
47   nettle_mpz_get_str_256(key_size, em, m);
48
49   /* Check format */
50   if (em[0] || em[1] != 2)
51     return 0;
52
53   terminator = memchr(em + 2, 0, key_size - 2);
54
55   if (!terminator)
56     return 0;
57   
58   padding = terminator - (em + 2);
59   if (padding < 8)
60     return 0;
61
62   message_length = key_size - 3 - padding;
63
64   if (*length < message_length)
65     return 0;
66   
67   memcpy(message, terminator + 1, message_length);
68   *length = message_length;
69
70   return 1;
71 }
72