add packaging
[platform/upstream/nettle.git] / salsa20-set-key.c
1 /* salsa20-set-key.c
2  *
3  * The Salsa20 stream cipher.
4  */
5
6 /* nettle, low-level cryptographics library
7  *
8  * Copyright (C) 2012 Simon Josefsson, Niels Möller
9  *  
10  * The nettle library is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or (at your
13  * option) any later version.
14  * 
15  * The nettle library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18  * License for more details.
19  * 
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with the nettle library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23  * MA 02111-1301, USA.
24  */
25
26 /* Based on:
27    salsa20-ref.c version 20051118
28    D. J. Bernstein
29    Public domain.
30 */
31
32 #if HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35
36 #include <assert.h>
37
38 #include "salsa20.h"
39
40 #include "macros.h"
41
42 void
43 salsa20_set_key(struct salsa20_ctx *ctx,
44                 unsigned length, const uint8_t *key)
45 {
46   static const uint32_t sigma[4] = {
47     /* "expand 32-byte k" */
48     0x61707865, 0x3320646e, 0x79622d32, 0x6b206574
49   };
50   static const uint32_t tau[4] = {
51     /* "expand 16-byte k" */
52     0x61707865, 0x3120646e, 0x79622d36, 0x6b206574
53   };
54   const uint32_t *constants;
55   
56   assert (length == SALSA20_MIN_KEY_SIZE || length == SALSA20_MAX_KEY_SIZE);
57
58   ctx->input[1] = LE_READ_UINT32(key + 0);
59   ctx->input[2] = LE_READ_UINT32(key + 4);
60   ctx->input[3] = LE_READ_UINT32(key + 8);
61   ctx->input[4] = LE_READ_UINT32(key + 12);
62   if (length == SALSA20_MAX_KEY_SIZE) { /* recommended */
63     ctx->input[11] = LE_READ_UINT32(key + 16);
64     ctx->input[12] = LE_READ_UINT32(key + 20);
65     ctx->input[13] = LE_READ_UINT32(key + 24);
66     ctx->input[14] = LE_READ_UINT32(key + 28);
67     constants = sigma;
68   } else { /* kbits == 128 */
69     ctx->input[11] = ctx->input[1];
70     ctx->input[12] = ctx->input[2];
71     ctx->input[13] = ctx->input[3];
72     ctx->input[14] = ctx->input[4];
73     constants = tau;
74   }
75   ctx->input[0]  = constants[0];
76   ctx->input[5]  = constants[1];
77   ctx->input[10] = constants[2];
78   ctx->input[15] = constants[3];
79 }
80
81 void
82 salsa20_set_iv(struct salsa20_ctx *ctx, const uint8_t *iv)
83 {
84   ctx->input[6] = LE_READ_UINT32(iv + 0);
85   ctx->input[7] = LE_READ_UINT32(iv + 4);
86   ctx->input[8] = 0;
87   ctx->input[9] = 0;
88 }