chiark / gitweb /
Merge branch 'mdw/aead'
[catacomb-python] / algorithms.c
1 /* -*-c-*-
2  *
3  * Symmetric cryptography
4  *
5  * (c) 2004 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of the Python interface to Catacomb.
11  *
12  * Catacomb/Python is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * Catacomb/Python is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Catacomb/Python; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "catacomb-python.h"
30 #include "algorithms.h"
31
32 /*----- Key sizes ---------------------------------------------------------*/
33
34 PyTypeObject *keysz_pytype;
35 PyTypeObject *keyszany_pytype, *keyszrange_pytype, *keyszset_pytype;
36 PyObject *sha_pyobj, *has160_pyobj;
37
38 #ifndef KSZ_OPMASK
39 #  define KSZ_OPMASK 0x1f
40 #endif
41
42 #ifndef KSZ_16BIT
43 #  define KSZ_16BIT 0x20
44 #endif
45
46 PyObject *keysz_pywrap(const octet *k)
47 {
48   unsigned op = *k++;
49 #define ARG(i) (op&KSZ_16BIT ? LOAD16(k + 2*(i)) : k[i])
50   switch (op&KSZ_OPMASK) {
51     case KSZ_ANY: {
52       keysz_pyobj *o = PyObject_New(keysz_pyobj, keyszany_pytype);
53       o->dfl = ARG(0);
54       return ((PyObject *)o);
55     } break;
56     case KSZ_RANGE: {
57       keyszrange_pyobj *o =
58         PyObject_New(keyszrange_pyobj, keyszrange_pytype);
59       o->dfl = ARG(0);
60       o->min = ARG(1);
61       o->max = ARG(2);
62       o->mod = ARG(3);
63       if (!o->mod) o->mod = 1;
64       return ((PyObject *)o);
65     } break;
66     case KSZ_SET: {
67       keyszset_pyobj *o =
68         PyObject_New(keyszset_pyobj, keyszset_pytype);
69       int i, n;
70       o->dfl = ARG(0);
71       for (i = 0; ARG(i); i++) ;
72       n = i; o->set = PyTuple_New(n);
73       for (i = 0; i < n; i++)
74         PyTuple_SET_ITEM(o->set, i, PyInt_FromLong(ARG(i)));
75       return ((PyObject *)o);
76     } break;
77     default:
78       abort();
79   }
80 #undef ARG
81 }
82
83 static PyObject *keyszany_pynew(PyTypeObject *ty,
84                                 PyObject *arg, PyObject *kw)
85 {
86   static const char *const kwlist[] = { "default", 0 };
87   int dfl;
88   keysz_pyobj *o;
89
90   if (!PyArg_ParseTupleAndKeywords(arg, kw, "i:new", KWLIST, &dfl))
91     goto end;
92   if (dfl < 0) VALERR("key size cannot be negative");
93   o = (keysz_pyobj *)ty->tp_alloc(ty, 0);
94   o->dfl = dfl;
95   return ((PyObject *)o);
96 end:
97   return (0);
98 }
99
100 static PyObject *keyszrange_pynew(PyTypeObject *ty,
101                                   PyObject *arg, PyObject *kw)
102 {
103   static const char *const kwlist[] = { "default", "min", "max", "mod", 0 };
104   int dfl, min = 0, max = 0, mod = 1;
105   keyszrange_pyobj *o;
106
107   if (!PyArg_ParseTupleAndKeywords(arg, kw, "i|iii:new", KWLIST,
108                                    &dfl, &min, &max, &mod))
109     goto end;
110   if (dfl < 0 || min < 0) VALERR("key size cannot be negative");
111   if (min > dfl || (max && dfl > max)) VALERR("bad key size bounds");
112   if (mod <= 0 || dfl%mod || min%mod || max%mod)
113     VALERR("bad key size modulus");
114   o = (keyszrange_pyobj *)ty->tp_alloc(ty, 0);
115   o->dfl = dfl;
116   o->min = min;
117   o->max = max;
118   o->mod = mod;
119   return ((PyObject *)o);
120 end:
121   return (0);
122 }
123
124 static PyObject *keyszset_pynew(PyTypeObject *ty,
125                                 PyObject *arg, PyObject *kw)
126 {
127   static const char *const kwlist[] = { "default", "set", 0 };
128   int dfl, i, n, xx;
129   PyObject *set = 0;
130   PyObject *x = 0, *l = 0;
131   keyszset_pyobj *o = 0;
132
133   if (!PyArg_ParseTupleAndKeywords(arg, kw, "i|O:new", KWLIST, &dfl, &set))
134     goto end;
135   if (!set) set = PyTuple_New(0);
136   else Py_INCREF(set);
137   if (!PySequence_Check(set)) TYERR("want a sequence");
138   n = PySequence_Size(set);
139   l = PyList_New(0);
140   if (PyErr_Occurred()) goto end;
141   if (dfl < 0) VALERR("key size cannot be negative");
142   x = PyInt_FromLong(dfl);
143   PyList_Append(l, x);
144   Py_DECREF(x);
145   x = 0;
146   for (i = 0; i < n; i++) {
147     if ((x = PySequence_GetItem(set, i)) == 0) goto end;
148     xx = PyInt_AsLong(x);
149     if (PyErr_Occurred()) goto end;
150     if (xx == dfl) continue;
151     if (xx < 0) VALERR("key size cannot be negative");
152     PyList_Append(l, x);
153     Py_DECREF(x);
154     x = 0;
155   }
156   Py_DECREF(set);
157   if ((set = PySequence_Tuple(l)) == 0) goto end;
158   o = (keyszset_pyobj *)ty->tp_alloc(ty, 0);
159   o->dfl = dfl;
160   o->set = set;
161   Py_INCREF(set);
162 end:
163   Py_XDECREF(set);
164   Py_XDECREF(l);
165   Py_XDECREF(x);
166   return ((PyObject *)o);
167 }
168
169 static PyObject *kaget_min(PyObject *me, void *hunoz)
170   { return (PyInt_FromLong(0)); }
171 #define kaget_max kaget_min
172
173 static PyObject *ksget_min(PyObject *me, void *hunoz)
174 {
175   PyObject *set = ((keyszset_pyobj *)me)->set;
176   int i, n, y, x = -1;
177   n = PyTuple_Size(set);
178   for (i = 0; i < n; i++) {
179     y = PyInt_AsLong(PyTuple_GetItem(set, i));
180     if (x == -1 || y < x) x = y;
181   }
182   return (PyInt_FromLong(x));
183 }
184
185 static PyObject *ksget_max(PyObject *me, void *hunoz)
186 {
187   PyObject *set = ((keyszset_pyobj *)me)->set;
188   int i, n, y, x = -1;
189   n = PyTuple_Size(set);
190   for (i = 0; i < n; i++) {
191     y = PyInt_AsLong(PyTuple_GetItem(set, i));
192     if (y > x) x = y;
193   }
194   return (PyInt_FromLong(x));
195 }
196
197 static PyMemberDef keysz_pymembers[] = {
198 #define MEMBERSTRUCT keysz_pyobj
199 #define default dfl /* ugh! */
200   MEMBER(default, T_INT, READONLY, "KSZ.default -> default key size")
201 #undef default
202 #undef MEMBERSTRUCT
203   { 0 }
204 };
205
206 static PyGetSetDef keyszany_pygetset[] = {
207 #define GETSETNAME(op, name) ka##op##_##name
208   GET   (min,                   "KSZ.min -> smallest allowed key size")
209   GET   (max,                   "KSZ.min -> largest allowed key size")
210 #undef GETSETNAME
211   { 0 }
212 };
213
214 static PyMemberDef keyszrange_pymembers[] = {
215 #define MEMBERSTRUCT keyszrange_pyobj
216   MEMBER(min, T_INT, READONLY,  "KSZ.min -> smallest allowed key size")
217   MEMBER(max, T_INT, READONLY,  "KSZ.min -> largest allowed key size")
218   MEMBER(mod, T_INT, READONLY,
219          "KSZ.mod -> key size must be a multiple of this")
220 #undef MEMBERSTRUCT
221   { 0 }
222 };
223
224 static PyGetSetDef keyszset_pygetset[] = {
225 #define GETSETNAME(op, name) ks##op##_##name
226   GET   (min,                   "KSZ.min -> smallest allowed key size")
227   GET   (max,                   "KSZ.min -> largest allowed key size")
228 #undef GETSETNAME
229   { 0 }
230 };
231
232 static PyMemberDef keyszset_pymembers[] = {
233 #define MEMBERSTRUCT keyszset_pyobj
234   MEMBER(set, T_OBJECT, READONLY,       "KSZ.set -> allowed key sizes")
235 #undef MEMBERSTRUCT
236   { 0 }
237 };
238
239 static PyTypeObject keysz_pytype_skel = {
240   PyObject_HEAD_INIT(0) 0,              /* Header */
241   "KeySZ",                              /* @tp_name@ */
242   sizeof(keysz_pyobj),                  /* @tp_basicsize@ */
243   0,                                    /* @tp_itemsize@ */
244
245   0,                                    /* @tp_dealloc@ */
246   0,                                    /* @tp_print@ */
247   0,                                    /* @tp_getattr@ */
248   0,                                    /* @tp_setattr@ */
249   0,                                    /* @tp_compare@ */
250   0,                                    /* @tp_repr@ */
251   0,                                    /* @tp_as_number@ */
252   0,                                    /* @tp_as_sequence@ */
253   0,                                    /* @tp_as_mapping@ */
254   0,                                    /* @tp_hash@ */
255   0,                                    /* @tp_call@ */
256   0,                                    /* @tp_str@ */
257   0,                                    /* @tp_getattro@ */
258   0,                                    /* @tp_setattro@ */
259   0,                                    /* @tp_as_buffer@ */
260   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
261     Py_TPFLAGS_BASETYPE,
262
263   /* @tp_doc@ */
264 "Key size constraints.  Abstract.",
265
266   0,                                    /* @tp_traverse@ */
267   0,                                    /* @tp_clear@ */
268   0,                                    /* @tp_richcompare@ */
269   0,                                    /* @tp_weaklistoffset@ */
270   0,                                    /* @tp_iter@ */
271   0,                                    /* @tp_iternext@ */
272   0,                                    /* @tp_methods@ */
273   keysz_pymembers,                      /* @tp_members@ */
274   0,                                    /* @tp_getset@ */
275   0,                                    /* @tp_base@ */
276   0,                                    /* @tp_dict@ */
277   0,                                    /* @tp_descr_get@ */
278   0,                                    /* @tp_descr_set@ */
279   0,                                    /* @tp_dictoffset@ */
280   0,                                    /* @tp_init@ */
281   PyType_GenericAlloc,                  /* @tp_alloc@ */
282   abstract_pynew,                       /* @tp_new@ */
283   0,                                    /* @tp_free@ */
284   0                                     /* @tp_is_gc@ */
285 };
286
287 static PyTypeObject keyszany_pytype_skel = {
288   PyObject_HEAD_INIT(0) 0,              /* Header */
289   "KeySZAny",                           /* @tp_name@ */
290   sizeof(keysz_pyobj),                  /* @tp_basicsize@ */
291   0,                                    /* @tp_itemsize@ */
292
293   0,                                    /* @tp_dealloc@ */
294   0,                                    /* @tp_print@ */
295   0,                                    /* @tp_getattr@ */
296   0,                                    /* @tp_setattr@ */
297   0,                                    /* @tp_compare@ */
298   0,                                    /* @tp_repr@ */
299   0,                                    /* @tp_as_number@ */
300   0,                                    /* @tp_as_sequence@ */
301   0,                                    /* @tp_as_mapping@ */
302   0,                                    /* @tp_hash@ */
303   0,                                    /* @tp_call@ */
304   0,                                    /* @tp_str@ */
305   0,                                    /* @tp_getattro@ */
306   0,                                    /* @tp_setattro@ */
307   0,                                    /* @tp_as_buffer@ */
308   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
309     Py_TPFLAGS_BASETYPE,
310
311   /* @tp_doc@ */
312 "KeySZAny(DEFAULT)\n\
313   Key size constraints.  This object imposes no constraints on size.",
314
315   0,                                    /* @tp_traverse@ */
316   0,                                    /* @tp_clear@ */
317   0,                                    /* @tp_richcompare@ */
318   0,                                    /* @tp_weaklistoffset@ */
319   0,                                    /* @tp_iter@ */
320   0,                                    /* @tp_iternext@ */
321   0,                                    /* @tp_methods@ */
322   0,                                    /* @tp_members@ */
323   keyszany_pygetset,                    /* @tp_getset@ */
324   0,                                    /* @tp_base@ */
325   0,                                    /* @tp_dict@ */
326   0,                                    /* @tp_descr_get@ */
327   0,                                    /* @tp_descr_set@ */
328   0,                                    /* @tp_dictoffset@ */
329   0,                                    /* @tp_init@ */
330   PyType_GenericAlloc,                  /* @tp_alloc@ */
331   keyszany_pynew,                       /* @tp_new@ */
332   0,                                    /* @tp_free@ */
333   0                                     /* @tp_is_gc@ */
334 };
335
336 static PyTypeObject keyszrange_pytype_skel = {
337   PyObject_HEAD_INIT(0) 0,              /* Header */
338   "KeySZRange",                         /* @tp_name@ */
339   sizeof(keyszrange_pyobj),             /* @tp_basicsize@ */
340   0,                                    /* @tp_itemsize@ */
341
342   0,                                    /* @tp_dealloc@ */
343   0,                                    /* @tp_print@ */
344   0,                                    /* @tp_getattr@ */
345   0,                                    /* @tp_setattr@ */
346   0,                                    /* @tp_compare@ */
347   0,                                    /* @tp_repr@ */
348   0,                                    /* @tp_as_number@ */
349   0,                                    /* @tp_as_sequence@ */
350   0,                                    /* @tp_as_mapping@ */
351   0,                                    /* @tp_hash@ */
352   0,                                    /* @tp_call@ */
353   0,                                    /* @tp_str@ */
354   0,                                    /* @tp_getattro@ */
355   0,                                    /* @tp_setattro@ */
356   0,                                    /* @tp_as_buffer@ */
357   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
358     Py_TPFLAGS_BASETYPE,
359
360   /* @tp_doc@ */
361 "KeySZRange(DEFAULT, [min = 0], [max = 0], [mod = 1])\n\
362   Key size constraints.  Key size must be between MIN and MAX inclusive,\n\
363   and be a multiple of MOD.",
364
365   0,                                    /* @tp_traverse@ */
366   0,                                    /* @tp_clear@ */
367   0,                                    /* @tp_richcompare@ */
368   0,                                    /* @tp_weaklistoffset@ */
369   0,                                    /* @tp_iter@ */
370   0,                                    /* @tp_iternext@ */
371   0,                                    /* @tp_methods@ */
372   keyszrange_pymembers,                 /* @tp_members@ */
373   0,                                    /* @tp_getset@ */
374   0,                                    /* @tp_base@ */
375   0,                                    /* @tp_dict@ */
376   0,                                    /* @tp_descr_get@ */
377   0,                                    /* @tp_descr_set@ */
378   0,                                    /* @tp_dictoffset@ */
379   0,                                    /* @tp_init@ */
380   PyType_GenericAlloc,                  /* @tp_alloc@ */
381   keyszrange_pynew,                     /* @tp_new@ */
382   0,                                    /* @tp_free@ */
383   0                                     /* @tp_is_gc@ */
384 };
385
386 static PyTypeObject keyszset_pytype_skel = {
387   PyObject_HEAD_INIT(0) 0,              /* Header */
388   "KeySZSet",                           /* @tp_name@ */
389   sizeof(keyszset_pyobj),               /* @tp_basicsize@ */
390   0,                                    /* @tp_itemsize@ */
391
392   0,                                    /* @tp_dealloc@ */
393   0,                                    /* @tp_print@ */
394   0,                                    /* @tp_getattr@ */
395   0,                                    /* @tp_setattr@ */
396   0,                                    /* @tp_compare@ */
397   0,                                    /* @tp_repr@ */
398   0,                                    /* @tp_as_number@ */
399   0,                                    /* @tp_as_sequence@ */
400   0,                                    /* @tp_as_mapping@ */
401   0,                                    /* @tp_hash@ */
402   0,                                    /* @tp_call@ */
403   0,                                    /* @tp_str@ */
404   0,                                    /* @tp_getattro@ */
405   0,                                    /* @tp_setattro@ */
406   0,                                    /* @tp_as_buffer@ */
407   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
408     Py_TPFLAGS_BASETYPE,
409
410   /* @tp_doc@ */
411 "KeySZSet(DEFAULT, SEQ)\n\
412   Key size constraints.  Key size must be DEFAULT or one in SEQ.",
413
414   0,                                    /* @tp_traverse@ */
415   0,                                    /* @tp_clear@ */
416   0,                                    /* @tp_richcompare@ */
417   0,                                    /* @tp_weaklistoffset@ */
418   0,                                    /* @tp_iter@ */
419   0,                                    /* @tp_iternext@ */
420   0,                                    /* @tp_methods@ */
421   keyszset_pymembers,                   /* @tp_members@ */
422   keyszset_pygetset,                    /* @tp_getset@ */
423   0,                                    /* @tp_base@ */
424   0,                                    /* @tp_dict@ */
425   0,                                    /* @tp_descr_get@ */
426   0,                                    /* @tp_descr_set@ */
427   0,                                    /* @tp_dictoffset@ */
428   0,                                    /* @tp_init@ */
429   PyType_GenericAlloc,                  /* @tp_alloc@ */
430   keyszset_pynew,                       /* @tp_new@ */
431   0,                                    /* @tp_free@ */
432   0                                     /* @tp_is_gc@ */
433 };
434
435 #define KSZCONVOP(op)                                                   \
436   static PyObject *meth__KeySZ_##op(PyObject *me, PyObject *arg)        \
437   {                                                                     \
438     double x, y;                                                        \
439     if (!PyArg_ParseTuple(arg, "Od:" #op, &me, &x)) return (0);         \
440     y = keysz_##op(x);                                                  \
441     return (PyFloat_FromDouble(y));                                     \
442   }
443 KSZCONVOP(fromdl)
444 KSZCONVOP(fromschnorr)
445 KSZCONVOP(fromif)
446 KSZCONVOP(fromec)
447 KSZCONVOP(todl)
448 KSZCONVOP(toschnorr)
449 KSZCONVOP(toif)
450 KSZCONVOP(toec)
451 #undef KSZCONVOP
452
453 /*----- Symmetric encryption ----------------------------------------------*/
454
455 PyTypeObject *gccipher_pytype, *gcipher_pytype;
456
457 CONVFUNC(gccipher, gccipher *, GCCIPHER_CC)
458 CONVFUNC(gcipher, gcipher *, GCIPHER_C)
459
460 PyObject *gcipher_pywrap(PyObject *cobj, gcipher *c)
461 {
462   gcipher_pyobj *g;
463   if (!cobj) cobj = gccipher_pywrap((/*unconst*/ gccipher *)GC_CLASS(c));
464   else Py_INCREF(cobj);
465   g = PyObject_NEW(gcipher_pyobj, (PyTypeObject *)cobj);
466   g->c = c;
467   return ((PyObject *)g);
468 }
469
470 static PyObject *gcipher_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
471 {
472   static const char *const kwlist[] = { "k", 0 };
473   char *k;
474   Py_ssize_t sz;
475
476   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#:new", KWLIST, &k, &sz))
477     goto end;
478   if (keysz(sz, GCCIPHER_CC(ty)->keysz) != sz) VALERR("bad key length");
479   return (gcipher_pywrap((PyObject *)ty,
480                          GC_INIT(GCCIPHER_CC(ty), k, sz)));
481 end:
482   return (0);
483 }
484
485 PyObject *gccipher_pywrap(gccipher *cc)
486 {
487   gccipher_pyobj *g = newtype(gccipher_pytype, 0, cc->name);
488   g->cc = cc;
489   g->ty.ht_type.tp_basicsize = sizeof(gcipher_pyobj);
490   g->ty.ht_type.tp_base = gcipher_pytype;
491   Py_INCREF(gcipher_pytype);
492   g->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
493                             Py_TPFLAGS_BASETYPE |
494                             Py_TPFLAGS_HEAPTYPE);
495   g->ty.ht_type.tp_alloc = PyType_GenericAlloc;
496   g->ty.ht_type.tp_free = 0;
497   g->ty.ht_type.tp_new = gcipher_pynew;
498   typeready(&g->ty.ht_type);
499   return ((PyObject *)g);
500 }
501
502 static void gcipher_pydealloc(PyObject *me)
503 {
504   GC_DESTROY(GCIPHER_C(me));
505   Py_DECREF(me->ob_type);
506   FREEOBJ(me);
507 }
508
509 static PyObject *gccget_name(PyObject *me, void *hunoz)
510   { return (PyString_FromString(GCCIPHER_CC(me)->name)); }
511
512 static PyObject *gccget_keysz(PyObject *me, void *hunoz)
513   { return (keysz_pywrap(GCCIPHER_CC(me)->keysz)); }
514
515 static PyObject *gccget_blksz(PyObject *me, void *hunoz)
516   { return (PyInt_FromLong(GCCIPHER_CC(me)->blksz)); }
517
518 static PyObject *gcmeth_encrypt(PyObject *me, PyObject *arg)
519 {
520   char *p;
521   Py_ssize_t sz;
522   PyObject *rc = 0;
523
524   if (!PyArg_ParseTuple(arg, "s#:encrypt", &p, &sz)) return (0);
525   rc = bytestring_pywrap(0, sz);
526   GC_ENCRYPT(GCIPHER_C(me), p, PyString_AS_STRING(rc), sz);
527   return (rc);
528 }
529
530 static PyObject *gcmeth_enczero(PyObject *me, PyObject *arg)
531 {
532   char *p;
533   int sz;
534   PyObject *rc = 0;
535
536   if (!PyArg_ParseTuple(arg, "i:enczero", &sz)) return (0);
537   rc = bytestring_pywrap(0, sz);
538   p = PyString_AS_STRING(rc);
539   memset(p, 0, sz);
540   GC_ENCRYPT(GCIPHER_C(me), p, p, sz);
541   return (rc);
542 }
543
544 static PyObject *gcmeth_decrypt(PyObject *me, PyObject *arg)
545 {
546   char *p;
547   Py_ssize_t sz;
548   PyObject *rc = 0;
549
550   if (!PyArg_ParseTuple(arg, "s#:decrypt", &p, &sz)) return (0);
551   rc = bytestring_pywrap(0, sz);
552   GC_DECRYPT(GCIPHER_C(me), p, PyString_AS_STRING(rc), sz);
553   return (rc);
554 }
555
556 static PyObject *gcmeth_deczero(PyObject *me, PyObject *arg)
557 {
558   char *p;
559   int sz;
560   PyObject *rc = 0;
561
562   if (!PyArg_ParseTuple(arg, "i:deczero", &sz)) return (0);
563   rc = bytestring_pywrap(0, sz);
564   p = PyString_AS_STRING(rc);
565   memset(p, 0, sz);
566   GC_DECRYPT(GCIPHER_C(me), p, p, sz);
567   return (rc);
568 }
569
570 static PyObject *gcmeth_setiv(PyObject *me, PyObject *arg)
571 {
572   char *p;
573   Py_ssize_t sz;
574
575   if (!PyArg_ParseTuple(arg, "s#:setiv", &p, &sz)) goto end;
576   if (!GCIPHER_C(me)->ops->setiv) VALERR("`setiv' not supported");
577   if (!GC_CLASS(GCIPHER_C(me))->blksz) VALERR("not a block cipher mode");
578   if (sz != GC_CLASS(GCIPHER_C(me))->blksz) VALERR("bad IV length");
579   GC_SETIV(GCIPHER_C(me), p);
580   RETURN_ME;
581 end:
582   return (0);
583 }
584
585 static PyObject *gcmeth_bdry(PyObject *me, PyObject *arg)
586 {
587   if (!PyArg_ParseTuple(arg, ":bdry")) goto end;
588   if (!GCIPHER_C(me)->ops->bdry) VALERR("`bdry' not supported");
589   if (!GC_CLASS(GCIPHER_C(me))->blksz) VALERR("not a block cipher mode");
590   GC_BDRY(GCIPHER_C(me));
591   RETURN_ME;
592 end:
593   return (0);
594 }
595
596 static PyGetSetDef gccipher_pygetset[] = {
597 #define GETSETNAME(op, name) gcc##op##_##name
598   GET   (keysz,                 "CC.keysz -> acceptable key sizes")
599   GET   (blksz,                 "CC.blksz -> block size, or zero")
600   GET   (name,                  "CC.name -> name of this kind of cipher")
601 #undef GETSETNAME
602   { 0 }
603 };
604
605 static PyMethodDef gcipher_pymethods[] = {
606 #define METHNAME(name) gcmeth_##name
607   METH  (encrypt,               "C.encrypt(PT) -> CT")
608   METH  (enczero,               "C.enczero(N) -> CT")
609   METH  (decrypt,               "C.decrypt(CT) -> PT")
610   METH  (deczero,               "C.deczero(N) -> PT")
611   METH  (setiv,                 "C.setiv(IV)")
612   METH  (bdry,                  "C.bdry()")
613 #undef METHNAME
614   { 0 }
615 };
616
617 static PyTypeObject gccipher_pytype_skel = {
618   PyObject_HEAD_INIT(0) 0,              /* Header */
619   "GCCipher",                           /* @tp_name@ */
620   sizeof(gccipher_pyobj),               /* @tp_basicsize@ */
621   0,                                    /* @tp_itemsize@ */
622
623   0,                                    /* @tp_dealloc@ */
624   0,                                    /* @tp_print@ */
625   0,                                    /* @tp_getattr@ */
626   0,                                    /* @tp_setattr@ */
627   0,                                    /* @tp_compare@ */
628   0,                                    /* @tp_repr@ */
629   0,                                    /* @tp_as_number@ */
630   0,                                    /* @tp_as_sequence@ */
631   0,                                    /* @tp_as_mapping@ */
632   0,                                    /* @tp_hash@ */
633   0,                                    /* @tp_call@ */
634   0,                                    /* @tp_str@ */
635   0,                                    /* @tp_getattro@ */
636   0,                                    /* @tp_setattro@ */
637   0,                                    /* @tp_as_buffer@ */
638   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
639     Py_TPFLAGS_BASETYPE,
640
641   /* @tp_doc@ */
642 "Symmetric cipher metaclass.",
643
644   0,                                    /* @tp_traverse@ */
645   0,                                    /* @tp_clear@ */
646   0,                                    /* @tp_richcompare@ */
647   0,                                    /* @tp_weaklistoffset@ */
648   0,                                    /* @tp_iter@ */
649   0,                                    /* @tp_iternext@ */
650   0,                                    /* @tp_methods@ */
651   0,                                    /* @tp_members@ */
652   gccipher_pygetset,                    /* @tp_getset@ */
653   0,                                    /* @tp_base@ */
654   0,                                    /* @tp_dict@ */
655   0,                                    /* @tp_descr_get@ */
656   0,                                    /* @tp_descr_set@ */
657   0,                                    /* @tp_dictoffset@ */
658   0,                                    /* @tp_init@ */
659   PyType_GenericAlloc,                  /* @tp_alloc@ */
660   abstract_pynew,                       /* @tp_new@ */
661   0,                                    /* @tp_free@ */
662   0                                     /* @tp_is_gc@ */
663 };
664
665 static PyTypeObject gcipher_pytype_skel = {
666   PyObject_HEAD_INIT(0) 0,              /* Header */
667   "GCipher",                            /* @tp_name@ */
668   sizeof(gcipher_pyobj),                /* @tp_basicsize@ */
669   0,                                    /* @tp_itemsize@ */
670
671   gcipher_pydealloc,                    /* @tp_dealloc@ */
672   0,                                    /* @tp_print@ */
673   0,                                    /* @tp_getattr@ */
674   0,                                    /* @tp_setattr@ */
675   0,                                    /* @tp_compare@ */
676   0,                                    /* @tp_repr@ */
677   0,                                    /* @tp_as_number@ */
678   0,                                    /* @tp_as_sequence@ */
679   0,                                    /* @tp_as_mapping@ */
680   0,                                    /* @tp_hash@ */
681   0,                                    /* @tp_call@ */
682   0,                                    /* @tp_str@ */
683   0,                                    /* @tp_getattro@ */
684   0,                                    /* @tp_setattro@ */
685   0,                                    /* @tp_as_buffer@ */
686   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
687     Py_TPFLAGS_BASETYPE,
688
689   /* @tp_doc@ */
690 "Symmetric cipher, abstract base class.",
691
692   0,                                    /* @tp_traverse@ */
693   0,                                    /* @tp_clear@ */
694   0,                                    /* @tp_richcompare@ */
695   0,                                    /* @tp_weaklistoffset@ */
696   0,                                    /* @tp_iter@ */
697   0,                                    /* @tp_iternext@ */
698   gcipher_pymethods,                    /* @tp_methods@ */
699   0,                                    /* @tp_members@ */
700   0,                                    /* @tp_getset@ */
701   0,                                    /* @tp_base@ */
702   0,                                    /* @tp_dict@ */
703   0,                                    /* @tp_descr_get@ */
704   0,                                    /* @tp_descr_set@ */
705   0,                                    /* @tp_dictoffset@ */
706   0,                                    /* @tp_init@ */
707   PyType_GenericAlloc,                  /* @tp_alloc@ */
708   abstract_pynew,                       /* @tp_new@ */
709   0,                                    /* @tp_free@ */
710   0                                     /* @tp_is_gc@ */
711 };
712
713 /*----- Authenticated encryption ------------------------------------------*/
714
715 PyTypeObject *gcaead_pytype, *gaeadkey_pytype;
716 PyTypeObject *gcaeadaad_pytype, *gaeadaad_pytype;
717 PyTypeObject *gcaeadenc_pytype, *gaeadenc_pytype;
718 PyTypeObject *gcaeaddec_pytype, *gaeaddec_pytype;
719
720 CONVFUNC(gcaead, gcaead *, GCAEAD_AEC)
721 CONVFUNC(gaeadkey, gaead_key *, GAEADKEY_K)
722
723 PyObject *gaeadkey_pywrap(PyObject *cobj, gaead_key *k)
724 {
725   gaeadkey_pyobj *gk;
726
727   if (!cobj) cobj = gcaead_pywrap((/*unconst*/ gcaead *)GAEAD_CLASS(k));
728   else Py_INCREF(cobj);
729   gk = PyObject_NEW(gaeadkey_pyobj, (PyTypeObject *)cobj);
730   gk->k = k;
731   return ((PyObject *)gk);
732 }
733
734 static PyObject *gaeadkey_pynew(PyTypeObject *ty,
735                                 PyObject *arg, PyObject *kw)
736 {
737   static const char *const kwlist[] = { "k", 0 };
738   char *k;
739   Py_ssize_t sz;
740
741   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#:new", KWLIST, &k, &sz))
742     goto end;
743   if (keysz(sz, GCAEAD_AEC(ty)->keysz) != sz) VALERR("bad key length");
744   return (gaeadkey_pywrap((PyObject *)ty,
745                           GAEAD_KEY(GCAEAD_AEC(ty), k, sz)));
746 end:
747   return (0);
748 }
749
750 PyObject *gcaead_pywrap(gcaead *aec)
751 {
752   gcaead_pyobj *gck;
753   gcaeadaad_pyobj *gca;
754   gcaeadenc_pyobj *gce;
755   gcaeaddec_pyobj *gcd;
756
757 #define MKTYPE(obj, thing, newfn, namefmt) do {                         \
758   (obj) = newtype(gcaead_pytype, 0, 0);                                 \
759   (obj)->ty.ht_name = PyString_FromFormat(namefmt, aec->name);          \
760   (obj)->ty.ht_type.tp_name = PyString_AS_STRING((obj)->ty.ht_name);    \
761   (obj)->ty.ht_type.tp_basicsize = sizeof(gaead##thing##_pyobj);        \
762   (obj)->ty.ht_type.tp_base = gaead##thing##_pytype;                    \
763   Py_INCREF(gaead##thing##_pytype);                                     \
764   (obj)->ty.ht_type.tp_flags =                                          \
765     (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE);   \
766   (obj)->ty.ht_type.tp_alloc = PyType_GenericAlloc;                     \
767   (obj)->ty.ht_type.tp_free = 0;                                        \
768   (obj)->ty.ht_type.tp_new = newfn;                                     \
769   typeready(&(obj)->ty.ht_type);                                        \
770 } while (0)
771
772   MKTYPE(gck, key, gaeadkey_pynew, "%s(key)");
773   MKTYPE(gca, aad, abstract_pynew, "%s(aad-hash)");
774   MKTYPE(gce, enc, abstract_pynew, "%s(encrypt)");
775   MKTYPE(gcd, dec, abstract_pynew, "%s(decrypt)");
776
777 #undef MKTYPE
778
779   gck->aec = aec; gck->aad = gca; gck->enc = gce; gck->dec = gcd;
780   gca->key = gce->key = gcd->key = gck;
781   return ((PyObject *)gck);
782 }
783
784 static void gaeadkey_pydealloc(PyObject *me)
785   { GAEAD_DESTROY(GAEADKEY_K(me)); Py_DECREF(me->ob_type); FREEOBJ(me); }
786
787 static PyObject *gcaeget_name(PyObject *me, void *hunoz)
788   { return (PyString_FromString(GCAEAD_AEC(me)->name)); }
789
790 static PyObject *gcaeget_keysz(PyObject *me, void *hunoz)
791   { return (keysz_pywrap(GCAEAD_AEC(me)->keysz)); }
792
793 static PyObject *gcaeget_noncesz(PyObject *me, void *hunoz)
794   { return (keysz_pywrap(GCAEAD_AEC(me)->noncesz)); }
795
796 static PyObject *gcaeget_tagsz(PyObject *me, void *hunoz)
797   { return (keysz_pywrap(GCAEAD_AEC(me)->tagsz)); }
798
799 static PyObject *gcaeget_blksz(PyObject *me, void *hunoz)
800   { return (PyInt_FromLong(GCAEAD_AEC(me)->blksz)); }
801
802 static PyObject *gcaeget_bufsz(PyObject *me, void *hunoz)
803   { return (PyInt_FromLong(GCAEAD_AEC(me)->bufsz)); }
804
805 static PyObject *gcaeget_ohd(PyObject *me, void *hunoz)
806   { return (PyInt_FromLong(GCAEAD_AEC(me)->ohd)); }
807
808 static PyObject *gcaeget_flags(PyObject *me, void *hunoz)
809   { return (PyInt_FromLong(GCAEAD_AEC(me)->f)); }
810
811 static PyGetSetDef gcaead_pygetset[] = {
812 #define GETSETNAME(op, name) gcae##op##_##name
813   GET   (keysz,                 "AEC.keysz -> acceptable key sizes")
814   GET   (noncesz,               "AEC.noncesz -> acceptable nonce sizes")
815   GET   (tagsz,                 "AEC.tagsz -> acceptable tag sizes")
816   GET   (blksz,                 "AEC.blksz -> block size, or zero")
817   GET   (bufsz,                 "AEC.bufsz -> amount of data buffered internally")
818   GET   (ohd,                   "AEC.ohd -> maximum encryption overhead")
819   GET   (name,                  "AEC.name -> name of this kind of AEAD scheme")
820   GET   (flags,                 "AEC.flags -> mask of `AEADF_...' flags")
821 #undef GETSETNAME
822   { 0 }
823 };
824
825 static PyObject *gaekmeth_aad(PyObject *me, PyObject *arg)
826 {
827   const gaead_key *k = GAEADKEY_K(me);
828   PyObject *rc = 0;
829
830   if (!PyArg_ParseTuple(arg, ":aad")) return (0);
831   if (k->ops->c->f&AEADF_AADNDEP)
832     VALERR("aad must be associated with enc/dec op");
833   rc = gaeadaad_pywrap((PyObject *)GCAEAD_AAD(me->ob_type),
834                        GAEAD_AAD(k), 0, 0);
835 end:
836   return (rc);
837 }
838
839 static int check_aead_encdec(const gcaead *aec, unsigned *f_out, size_t nsz,
840                              PyObject *hszobj, size_t *hsz_out,
841                              PyObject *mszobj, size_t *msz_out,
842                              PyObject *tszobj, size_t *tsz_out)
843 {
844   unsigned f = 0, miss;
845   int rc = -1;
846
847   if (hszobj != Py_None)
848     { f |= AEADF_PCHSZ; if (!convszt(hszobj, hsz_out)) goto end; }
849   if (mszobj != Py_None)
850     { f |= AEADF_PCMSZ; if (!convszt(mszobj, msz_out)) goto end; }
851   if (tszobj != Py_None)
852     { f |= AEADF_PCTSZ; if (!convszt(tszobj, tsz_out)) goto end; }
853   miss = aec->f&~f;
854   if (miss&AEADF_PCHSZ) VALERR("header length precommitment required");
855   if (miss&AEADF_PCMSZ) VALERR("message length precommitment required");
856   if (miss&AEADF_PCTSZ) VALERR("tag length precommitment required");
857   if (keysz(nsz, aec->noncesz) != nsz) VALERR("bad nonce length");
858   if (tszobj != Py_None && keysz(*tsz_out, aec->tagsz) != *tsz_out)
859     VALERR("bad tag length");
860   *f_out = f | aec->f; rc = 0;
861 end:
862   return (rc);
863 }
864
865 static PyObject *gaekmeth_enc(PyObject *me, PyObject *arg, PyObject *kw)
866 {
867   static const char *const kwlist[] = { "nonce", "hsz", "msz", "tsz", 0 };
868   const gaead_key *k = GAEADKEY_K(me);
869   gaead_enc *e;
870   PyObject *rc = 0;
871   char *n; Py_ssize_t nsz;
872   PyObject *hszobj = Py_None, *mszobj = Py_None, *tszobj = Py_None;
873   size_t hsz = 0, msz = 0, tsz = 0;
874   unsigned f;
875
876   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|OOO:enc", KWLIST,
877                                    &n, &nsz, &hszobj, &mszobj, &tszobj))
878     goto end;
879   if (check_aead_encdec(k->ops->c, &f, nsz,
880                         hszobj, &hsz, mszobj, &msz, tszobj, &tsz))
881     goto end;
882   e = GAEAD_ENC(GAEADKEY_K(me), n, nsz, hsz, msz, tsz);
883   if (!e) VALERR("bad aead parameter combination");
884   rc = gaeadenc_pywrap((PyObject *)GCAEAD_ENC(me->ob_type),
885                        e, f, hsz, msz, tsz);
886 end:
887   return (rc);
888 }
889
890 static PyObject *gaekmeth_dec(PyObject *me, PyObject *arg, PyObject *kw)
891 {
892   static const char *const kwlist[] = { "nonce", "hsz", "csz", "tsz", 0 };
893   const gaead_key *k = GAEADKEY_K(me);
894   gaead_dec *d;
895   PyObject *rc = 0;
896   char *n; Py_ssize_t nsz;
897   PyObject *hszobj = Py_None, *cszobj = Py_None, *tszobj = Py_None;
898   size_t hsz = 0, csz = 0, tsz = 0;
899   unsigned f;
900
901   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|OOO:dec", KWLIST,
902                                    &n, &nsz, &hszobj, &cszobj, &tszobj))
903     goto end;
904   if (check_aead_encdec(k->ops->c, &f, nsz,
905                         hszobj, &hsz, cszobj, &csz, tszobj, &tsz))
906     goto end;
907   d = GAEAD_DEC(GAEADKEY_K(me), n, nsz, hsz, csz, tsz);
908   if (!d) VALERR("bad aead parameter combination");
909   rc = gaeaddec_pywrap((PyObject *)GCAEAD_DEC(me->ob_type),
910                        d, f, hsz, csz, tsz);
911 end:
912   return (rc);
913 }
914
915 static PyMethodDef gaeadkey_pymethods[] = {
916 #define METHNAME(name) gaekmeth_##name
917   METH  (aad,                   "KEY.aad() -> AAD")
918   KWMETH(enc,                   "KEY.enc(NONCE, [hsz], [msz], [tsz]) -> ENC")
919   KWMETH(dec,                   "KEY.dec(NONCE, [hsz], [csz], [tsz]) -> DEC")
920 #undef METHNAME
921   { 0 }
922 };
923
924 PyObject *gaeadaad_pywrap(PyObject *cobj, gaead_aad *a,
925                           unsigned f, size_t hsz)
926 {
927   gaeadaad_pyobj *ga;
928
929   assert(cobj); Py_INCREF(cobj);
930   ga = PyObject_NEW(gaeadaad_pyobj, (PyTypeObject *)cobj);
931   ga->a = a; ga->f = f; ga->hsz = hsz; ga->hlen = 0;
932   return ((PyObject *)ga);
933 }
934
935 static void gaeadaad_pydealloc(PyObject *me)
936 {
937   gaeadaad_pyobj *ga = (gaeadaad_pyobj *)me;
938
939   if (ga->a) GAEAD_DESTROY(ga->a);
940   Py_DECREF(me->ob_type); FREEOBJ(me);
941 }
942
943 static int gaea_check(PyObject *me)
944 {
945   gaeadaad_pyobj *ga = (gaeadaad_pyobj *)me;
946   int rc = -1;
947
948   if ((ga->f&AEADF_DEAD) || !ga->a) VALERR("aad object no longer active");
949   rc = 0;
950 end:
951   return (rc);
952 }
953
954 static void gaea_invalidate(gaeadaad_pyobj *ga)
955   { if (ga) ga->f |= AEADF_DEAD; }
956
957 static void gaea_sever(gaeadaad_pyobj **ga_inout)
958 {
959   gaeadaad_pyobj *ga = *ga_inout;
960   if (ga) { ga->f |= AEADF_DEAD; ga->a = 0; Py_DECREF(ga); *ga_inout = 0; }
961 }
962
963 static PyObject *gaeaget_hsz(PyObject *me, void *hunoz)
964 {
965   if (gaea_check(me)) return (0);
966   else if (GAEADAAD_F(me)&AEADF_PCHSZ) return getulong(GAEADAAD_HSZ(me));
967   else RETURN_NONE;
968 }
969
970 static PyObject *gaeaget_hlen(PyObject *me, void *hunoz)
971   { return (gaea_check(me) ? 0 : getulong(GAEADAAD_HLEN(me))); }
972
973 static PyGetSetDef gaeadaad_pygetset[] = {
974 #define GETSETNAME(op, name) gaea##op##_##name
975   GET   (hsz,                   "AAD.hsz -> precommitted header length or `None'")
976   GET   (hlen,                  "AAD.hlen -> header length so far")
977 #undef GETSETNAME
978   { 0 }
979 };
980
981 static PyObject *gaeameth_copy(PyObject *me, PyObject *arg)
982 {
983   PyObject *rc = 0;
984
985   if (!PyArg_ParseTuple(arg, ":copy")) goto end;
986   if (gaea_check(me)) goto end;
987   if (GAEADAAD_F(me)&AEADF_AADNDEP)
988     VALERR("can't duplicate nonce-dependent aad");
989   rc = gaeadaad_pywrap((PyObject *)me->ob_type,
990                        GAEAD_DUP(GAEADAAD_A(me)), 0, 0);
991 end:
992   return (rc);
993 }
994
995 static int gaeadaad_hash(PyObject *me, const void *h, size_t hsz)
996 {
997   gaeadaad_pyobj *ga = (gaeadaad_pyobj *)me;
998   int rc = -1;
999
1000   if (gaea_check(me)) goto end;
1001   if ((ga->f&AEADF_NOAAD) && hsz)
1002     VALERR("header data not permitted");
1003   if ((ga->f&AEADF_PCHSZ) && hsz > ga->hsz - ga->hlen)
1004     VALERR("too large for precommitted header length");
1005   GAEAD_HASH(ga->a, h, hsz); ga->hlen += hsz;
1006   rc = 0;
1007 end:
1008   return (rc);
1009 }
1010
1011
1012 static PyObject *gaeameth_hash(PyObject *me, PyObject *arg)
1013 {
1014   char *h; Py_ssize_t hsz;
1015
1016   if (!PyArg_ParseTuple(arg, "s#:hash", &h, &hsz)) return (0);
1017   if (gaeadaad_hash(me, h, hsz)) return (0);
1018   RETURN_ME;
1019 }
1020
1021 #define GAEAMETH_HASHU_(n, W, w)                                        \
1022   static PyObject *gaeameth_hashu##w(PyObject *me, PyObject *arg)       \
1023   {                                                                     \
1024     uint##n x; octet b[SZ_##W];                                         \
1025     if (!PyArg_ParseTuple(arg, "O&:hashu" #w, convu##n, &x)) return (0); \
1026     STORE##W(b, x); if (gaeadaad_hash(me, b, sizeof(b))) return (0);    \
1027     RETURN_ME;                                                          \
1028   }
1029 DOUINTCONV(GAEAMETH_HASHU_)
1030
1031 #define GAEAMETH_HASHBUF_(n, W, w)                                      \
1032   static PyObject *gaeameth_hashbuf##w(PyObject *me, PyObject *arg)     \
1033   {                                                                     \
1034     char *p; Py_ssize_t sz; octet b[SZ_##W];                            \
1035     if (!PyArg_ParseTuple(arg, "s#:hashbuf" #w, &p, &sz)) goto end;     \
1036     if (sz > MASK##n) TYERR("string too long");                         \
1037     STORE##W(b, sz); if (gaeadaad_hash(me, b, sizeof(b))) goto end;     \
1038     if (gaeadaad_hash(me, p, sz)) goto end;                             \
1039     RETURN_ME;                                                          \
1040   end:                                                                  \
1041     return (0);                                                         \
1042   }
1043 DOUINTCONV(GAEAMETH_HASHBUF_)
1044
1045 static PyObject *gaeameth_hashstrz(PyObject *me, PyObject *arg)
1046 {
1047   char *p;
1048   if (!PyArg_ParseTuple(arg, "s:hashstrz", &p)) return (0);
1049   if (gaeadaad_hash(me, p, strlen(p) + 1)) return (0);
1050   RETURN_ME;
1051 }
1052
1053 static PyMethodDef gaeadaad_pymethods[] = {
1054 #define METHNAME(name) gaeameth_##name
1055   METH  (copy,                  "AAD.copy() -> AAD'")
1056   METH  (hash,                  "AAD.hash(H)")
1057 #define METHU_(n, W, w) METH(hashu##w, "AAD.hashu" #w "(WORD)")
1058   DOUINTCONV(METHU_)
1059 #undef METHU_
1060 #define METHBUF_(n, W, w) METH(hashbuf##w, "AAD.hashbuf" #w "(BYTES)")
1061   DOUINTCONV(METHBUF_)
1062 #undef METHBUF_
1063   METH  (hashstrz,              "AAD.hashstrz(STRING)")
1064 #undef METHNAME
1065   { 0 }
1066 };
1067
1068 PyObject *gaeadenc_pywrap(PyObject *cobj, gaead_enc *e, unsigned f,
1069                           size_t hsz, size_t msz, size_t tsz)
1070 {
1071   gaeadenc_pyobj *ge;
1072
1073   assert(cobj); Py_INCREF(cobj);
1074   ge = PyObject_NEW(gaeadenc_pyobj, (PyTypeObject *)cobj);
1075   ge->e = e; ge->f = f; ge->hsz = hsz; ge->msz = msz; ge->tsz = tsz;
1076   ge->aad = 0; ge->mlen = 0;
1077   return ((PyObject *)ge);
1078 }
1079
1080 static void gaeadenc_pydealloc(PyObject *me)
1081 {
1082   gaeadenc_pyobj *ge = (gaeadenc_pyobj *)me;
1083
1084   gaea_sever(&ge->aad); GAEAD_DESTROY(ge->e);
1085   Py_DECREF(me->ob_type); FREEOBJ(me);
1086 }
1087
1088 static PyObject *gaeeget_hsz(PyObject *me, void *hunoz)
1089 {
1090   if (GAEADENC_F(me)&AEADF_PCHSZ) return getulong(GAEADENC_HSZ(me));
1091   else RETURN_NONE;
1092 }
1093
1094 static PyObject *gaeeget_msz(PyObject *me, void *hunoz)
1095 {
1096   if (GAEADENC_F(me)&AEADF_PCMSZ) return getulong(GAEADENC_MSZ(me));
1097   else RETURN_NONE;
1098 }
1099
1100 static PyObject *gaeeget_tsz(PyObject *me, void *hunoz)
1101 {
1102   if (GAEADENC_F(me)&AEADF_PCTSZ) return getulong(GAEADENC_TSZ(me));
1103   else RETURN_NONE;
1104 }
1105
1106 static PyObject *gaeeget_mlen(PyObject *me, void *hunoz)
1107   { return getulong(GAEADENC_MLEN(me)); }
1108
1109 static PyGetSetDef gaeadenc_pygetset[] = {
1110 #define GETSETNAME(op, name) gaee##op##_##name
1111   GET   (hsz,                   "ENC.hsz -> precommitted header length or `None'")
1112   GET   (msz,                   "ENC.msz -> precommitted message length or `None'")
1113   GET   (tsz,                   "ENC.tsz -> precommitted tag length or `None'")
1114   GET   (mlen,                  "ENC.mlen -> message length so far")
1115 #undef GETSETNAME
1116   { 0 }
1117 };
1118
1119 static PyObject *gaeemeth_aad(PyObject *me, PyObject *arg)
1120 {
1121   gaeadenc_pyobj *ge = (gaeadenc_pyobj *)me;
1122   PyObject *rc = 0;
1123
1124   if (!PyArg_ParseTuple(arg, ":aad")) return (0);
1125   if (!(ge->f&AEADF_AADNDEP))
1126     rc = gaeadaad_pywrap((PyObject *)GCAEADENC_KEY(ge->ob_type)->aad,
1127                          GAEAD_AAD(ge->e), 0, 0);
1128   else {
1129     if ((ge->f&AEADF_AADFIRST) && ge->mlen)
1130       VALERR("too late for aad");
1131     if (!ge->aad)
1132       ge->aad = (gaeadaad_pyobj *)
1133         gaeadaad_pywrap((PyObject *)GCAEADENC_KEY(ge->ob_type)->aad,
1134                         GAEAD_AAD(ge->e), ge->f&AEADF_PCHSZ, ge->hsz);
1135     Py_INCREF(ge->aad);
1136     rc = (PyObject *)ge->aad;
1137   }
1138 end:
1139   return (rc);
1140 }
1141
1142 static PyObject *gaeemeth_reinit(PyObject *me, PyObject *arg, PyObject *kw)
1143 {
1144   static const char *const kwlist[] = { "nonce", "hsz", "msz", "tsz", 0 };
1145   gaeadenc_pyobj *ge = (gaeadenc_pyobj *)me;
1146   char *n; Py_ssize_t nsz;
1147   PyObject *hszobj = Py_None, *mszobj = Py_None, *tszobj = Py_None;
1148   size_t hsz = 0, msz = 0, tsz = 0;
1149   unsigned f;
1150
1151   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|OOO:enc", KWLIST,
1152                                    &n, &nsz, &hszobj, &mszobj, &tszobj))
1153     goto end;
1154   if (check_aead_encdec(ge->e->ops->c, &f, nsz,
1155                         hszobj, &hsz, mszobj, &msz, tszobj, &tsz))
1156     goto end;
1157   if (GAEAD_REINIT(ge->e, n, nsz, hsz, msz, tsz))
1158     VALERR("bad aead parameter combination");
1159   gaea_sever(&ge->aad);
1160   ge->f = f; ge->hsz = hsz; ge->msz = msz; ge->tsz = tsz;
1161 end:
1162   return (0);
1163 }
1164
1165 static PyObject *gaeemeth_encrypt(PyObject *me, PyObject *arg)
1166 {
1167   gaeadenc_pyobj *ge = (gaeadenc_pyobj *)me;
1168   char *m; Py_ssize_t msz;
1169   char *c = 0; size_t csz; buf b;
1170   int err;
1171   PyObject *rc = 0;
1172
1173   if (!PyArg_ParseTuple(arg, "s#:encrypt", &m, &msz)) goto end;
1174   if (ge->f&AEADF_AADFIRST) {
1175     if ((ge->f&AEADF_PCHSZ) && (ge->aad ? ge->aad->hlen : 0) != ge->hsz)
1176       VALERR("header doesn't match precommitted length");
1177     gaea_invalidate(ge->aad);
1178   }
1179   if ((ge->f&AEADF_PCMSZ) && msz > ge->msz - ge->mlen)
1180     VALERR("too large for precommitted message length");
1181   csz = msz + ge->e->ops->c->bufsz; c = xmalloc(csz); buf_init(&b, c, csz);
1182   err = GAEAD_ENCRYPT(ge->e, m, msz, &b); assert(!err); (void)err;
1183   buf_flip(&b); rc = bytestring_pywrapbuf(&b); ge->mlen += msz;
1184 end:
1185   xfree(c);
1186   return (rc);
1187 }
1188
1189 static PyObject *gaeemeth_done(PyObject *me, PyObject *arg, PyObject *kw)
1190 {
1191   static const char *const kwlist[] = { "tsz", "aad", 0 };
1192   gaeadenc_pyobj *ge = (gaeadenc_pyobj *)me;
1193   PyObject *aad = Py_None;
1194   char *c = 0; size_t csz; buf b;
1195   PyObject *tszobj = Py_None; PyObject *tag; size_t tsz;
1196   int err;
1197   PyObject *rc = 0;
1198
1199   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|OO:done", KWLIST,
1200                                    &tszobj, &aad))
1201     goto end;
1202   if (tszobj != Py_None && !convszt(tszobj, &tsz)) goto end;
1203   if (aad != Py_None &&
1204       !PyObject_TypeCheck(aad,
1205                           (PyTypeObject *)GCAEADENC_KEY(me->ob_type)->aad))
1206     TYERR("wanted aad");
1207   if ((ge->f&AEADF_AADNDEP) && aad != Py_None && aad != (PyObject *)ge->aad)
1208     VALERR("mismatched aad");
1209   if ((ge->f&AEADF_PCHSZ) &&
1210       (aad == Py_None ? 0 : GAEADAAD_HLEN(aad)) != ge->hsz)
1211     VALERR("header doesn't match precommitted length");
1212   if ((ge->f&AEADF_PCMSZ) && ge->mlen != ge->msz)
1213     VALERR("message doesn't match precommitted length");
1214   if (tszobj == Py_None) {
1215     if (ge->f&AEADF_PCTSZ) tsz = ge->tsz;
1216     else tsz = keysz(0, ge->e->ops->c->tagsz);
1217   } else {
1218     if ((ge->f&AEADF_PCTSZ) && tsz != ge->tsz)
1219       VALERR("tag length doesn't match precommitted value");
1220     if (keysz(tsz, ge->e->ops->c->tagsz) != tsz) VALERR("bad tag length");
1221   }
1222   csz = ge->e->ops->c->bufsz; c = xmalloc(csz); buf_init(&b, c, csz);
1223   tag = bytestring_pywrap(0, tsz);
1224   err = GAEAD_DONE(ge->e, aad == Py_None ? 0 : GAEADAAD_A(aad), &b,
1225                    PyString_AS_STRING(tag), tsz);
1226   assert(!err); (void)err;
1227   buf_flip(&b); rc = Py_BuildValue("NN", bytestring_pywrapbuf(&b), tag);
1228 end:
1229   xfree(c);
1230   return (rc);
1231 }
1232
1233 static PyMethodDef gaeadenc_pymethods[] = {
1234 #define METHNAME(name) gaeemeth_##name
1235   METH  (aad,                   "ENC.aad() -> AAD")
1236   KWMETH(reinit,                "ENC.reinit(NONCE, [hsz], [msz], [tsz])")
1237   METH  (encrypt,               "ENC.encrypt(MSG) -> CT")
1238   KWMETH(done,                  "ENC.done([tsz], [aad]) -> CT, TAG")
1239 #undef METHNAME
1240   { 0 }
1241 };
1242
1243 PyObject *gaeaddec_pywrap(PyObject *cobj, gaead_dec *d, unsigned f,
1244                           size_t hsz, size_t csz, size_t tsz)
1245 {
1246   gaeaddec_pyobj *gd;
1247   assert(cobj); Py_INCREF(cobj);
1248   gd = PyObject_NEW(gaeaddec_pyobj, (PyTypeObject *)cobj);
1249   gd->d = d; gd->f = f; gd->hsz = hsz; gd->csz = csz; gd->tsz = tsz;
1250   gd->aad = 0; gd->clen = 0;
1251   return ((PyObject *)gd);
1252 }
1253
1254 static void gaeaddec_pydealloc(PyObject *me)
1255 {
1256   gaeaddec_pyobj *gd = (gaeaddec_pyobj *)me;
1257
1258   gaea_sever(&gd->aad); GAEAD_DESTROY(GAEADDEC_D(me));
1259   Py_DECREF(me->ob_type); FREEOBJ(me);
1260 }
1261
1262 static PyObject *gaedget_hsz(PyObject *me, void *hunoz)
1263 {
1264   if (GAEADDEC_F(me)&AEADF_PCHSZ) return getulong(GAEADDEC_HSZ(me));
1265   else RETURN_NONE;
1266 }
1267
1268 static PyObject *gaedget_csz(PyObject *me, void *hunoz)
1269 {
1270   if (GAEADDEC_F(me)&AEADF_PCMSZ) return getulong(GAEADDEC_CSZ(me));
1271   else RETURN_NONE;
1272 }
1273
1274 static PyObject *gaedget_tsz(PyObject *me, void *hunoz)
1275 {
1276   if (GAEADDEC_F(me)&AEADF_PCTSZ) return getulong(GAEADDEC_TSZ(me));
1277   else RETURN_NONE;
1278 }
1279
1280 static PyObject *gaedget_clen(PyObject *me, void *hunoz)
1281   { return getulong(GAEADDEC_CLEN(me)); }
1282
1283 static PyGetSetDef gaeaddec_pygetset[] = {
1284 #define GETSETNAME(op, name) gaed##op##_##name
1285   GET   (hsz,                   "DEC.hsz -> precommitted header length or `None'")
1286   GET   (csz,                   "DEC.csz -> precommitted ciphertext length or `None'")
1287   GET   (tsz,                   "DEC.tsz -> precommitted tag length or `None'")
1288   GET   (clen,                  "DEC.clen -> ciphertext length so far")
1289 #undef GETSETNAME
1290   { 0 }
1291 };
1292
1293 static PyObject *gaedmeth_aad(PyObject *me, PyObject *arg)
1294 {
1295   gaeaddec_pyobj *gd = (gaeaddec_pyobj *)me;
1296
1297   if (!PyArg_ParseTuple(arg, ":aad")) return (0);
1298   if (!(gd->f&AEADF_AADNDEP))
1299     return (gaeadaad_pywrap((PyObject *)GCAEADDEC_KEY(gd->ob_type)->aad,
1300                             GAEAD_AAD(gd->d), 0, 0));
1301   else {
1302     if (!gd->aad)
1303       gd->aad = (gaeadaad_pyobj *)
1304         gaeadaad_pywrap((PyObject *)GCAEADENC_KEY(gd->ob_type)->aad,
1305                         GAEAD_AAD(gd->d), gd->f&AEADF_PCHSZ, gd->hsz);
1306     Py_INCREF(gd->aad);
1307     return ((PyObject *)gd->aad);
1308   }
1309 }
1310
1311 static PyObject *gaedmeth_reinit(PyObject *me, PyObject *arg, PyObject *kw)
1312 {
1313   static const char *const kwlist[] = { "nonce", "hsz", "csz", "tsz", 0 };
1314   gaeaddec_pyobj *gd = (gaeaddec_pyobj *)me;
1315   char *n; Py_ssize_t nsz;
1316   PyObject *hszobj = Py_None, *cszobj = Py_None, *tszobj = Py_None;
1317   size_t hsz = 0, csz = 0, tsz = 0;
1318   unsigned f;
1319
1320   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|OOO:enc", KWLIST,
1321                                    &n, &nsz, &hszobj, &cszobj, &tszobj))
1322     goto end;
1323   if (check_aead_encdec(gd->d->ops->c, &f, nsz,
1324                         hszobj, &hsz, cszobj, &csz, tszobj, &tsz))
1325     goto end;
1326   if (GAEAD_REINIT(gd->d, n, nsz, hsz, csz, tsz))
1327     VALERR("bad aead parameter combination");
1328   gaea_sever(&gd->aad);
1329   gd->f = f; gd->hsz = hsz; gd->csz = csz; gd->tsz = tsz;
1330 end:
1331   return (0);
1332 }
1333
1334 static PyObject *gaedmeth_decrypt(PyObject *me, PyObject *arg)
1335 {
1336   gaeaddec_pyobj *gd = (gaeaddec_pyobj *)me;
1337   char *c; Py_ssize_t csz;
1338   char *m = 0; size_t msz; buf b;
1339   int err;
1340   PyObject *rc = 0;
1341
1342   if (!PyArg_ParseTuple(arg, "s#:decrypt", &c, &csz)) goto end;
1343   if (gd->f&AEADF_AADFIRST) {
1344     if ((gd->f&AEADF_PCHSZ) && (gd->aad ? gd->aad->hlen : 0) != gd->hsz)
1345       VALERR("header doesn't match precommitted length");
1346     gaea_invalidate(gd->aad);
1347   }
1348   if ((gd->f&AEADF_PCMSZ) && csz > gd->csz - gd->clen)
1349     VALERR("too large for precommitted message length");
1350   msz = csz + gd->d->ops->c->bufsz; m = xmalloc(msz); buf_init(&b, m, msz);
1351   err = GAEAD_DECRYPT(gd->d, c, csz, &b); assert(!err); (void)err;
1352   buf_flip(&b); rc = bytestring_pywrapbuf(&b); gd->clen += csz;
1353 end:
1354   xfree(m);
1355   return (rc);
1356 }
1357
1358 static PyObject *gaedmeth_done(PyObject *me, PyObject *arg, PyObject *kw)
1359 {
1360   static const char *const kwlist[] = { "tag", "aad", 0 };
1361   gaeaddec_pyobj *gd = (gaeaddec_pyobj *)me;
1362   PyObject *aad = Py_None;
1363   char *t; Py_ssize_t tsz;
1364   char *m = 0; size_t msz; buf b;
1365   int err;
1366   PyObject *rc = 0;
1367
1368   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|O:done", KWLIST,
1369                                    &t, &tsz, &aad))
1370     goto end;
1371   if (aad != Py_None &&
1372       !PyObject_TypeCheck(aad,
1373                           (PyTypeObject *)GCAEADENC_KEY(me->ob_type)->aad))
1374     TYERR("wanted aad");
1375   if ((gd->f&AEADF_AADNDEP) && aad != Py_None && aad != (PyObject *)gd->aad)
1376     VALERR("mismatched aad");
1377   if ((gd->f&AEADF_PCHSZ) &&
1378       (aad == Py_None ? 0 : GAEADAAD_HLEN(aad)) != gd->hsz)
1379     VALERR("header doesn't match precommitted length");
1380   if ((gd->f&AEADF_PCMSZ) && gd->clen != gd->csz)
1381     VALERR("message doesn't match precommitted length");
1382   if ((gd->f&AEADF_PCTSZ) && tsz != gd->tsz)
1383     VALERR("tag length doesn't match precommitted value");
1384   if (keysz(tsz, gd->d->ops->c->tagsz) != tsz) VALERR("bad tag length");
1385   msz = gd->d->ops->c->bufsz; m = xmalloc(msz); buf_init(&b, m, msz);
1386   err = GAEAD_DONE(gd->d, aad == Py_None ? 0 : GAEADAAD_A(aad), &b, t, tsz);
1387   assert(err >= 0);
1388   if (!err) VALERR("decryption failed");
1389   buf_flip(&b); rc = bytestring_pywrapbuf(&b);
1390 end:
1391   xfree(m);
1392   return (rc);
1393 }
1394
1395 static PyMethodDef gaeaddec_pymethods[] = {
1396 #define METHNAME(name) gaedmeth_##name
1397   METH  (aad,                   "DEC.aad() -> AAD")
1398   KWMETH(reinit,                "DEC.reinit(NONCE, [hsz], [csz], [tsz])")
1399   METH  (decrypt,               "DEC.decrypt(CT) -> MSG")
1400   KWMETH(done,                  "DEC.done(TAG, [aad]) -> MSG | None")
1401 #undef METHNAME
1402   { 0 }
1403 };
1404
1405 static PyTypeObject gcaead_pytype_skel = {
1406   PyObject_HEAD_INIT(0) 0,              /* Header */
1407   "GCAEAD",                             /* @tp_name@ */
1408   sizeof(gcaead_pyobj),                 /* @tp_basicsize@ */
1409   0,                                    /* @tp_itemsize@ */
1410
1411   0,                                    /* @tp_dealloc@ */
1412   0,                                    /* @tp_print@ */
1413   0,                                    /* @tp_getattr@ */
1414   0,                                    /* @tp_setattr@ */
1415   0,                                    /* @tp_compare@ */
1416   0,                                    /* @tp_repr@ */
1417   0,                                    /* @tp_as_number@ */
1418   0,                                    /* @tp_as_sequence@ */
1419   0,                                    /* @tp_as_mapping@ */
1420   0,                                    /* @tp_hash@ */
1421   0,                                    /* @tp_call@ */
1422   0,                                    /* @tp_str@ */
1423   0,                                    /* @tp_getattro@ */
1424   0,                                    /* @tp_setattro@ */
1425   0,                                    /* @tp_as_buffer@ */
1426   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1427     Py_TPFLAGS_BASETYPE,
1428
1429   /* @tp_doc@ */
1430 "Authenticated encryption (key) metaclass.",
1431
1432   0,                                    /* @tp_traverse@ */
1433   0,                                    /* @tp_clear@ */
1434   0,                                    /* @tp_richcompare@ */
1435   0,                                    /* @tp_weaklistoffset@ */
1436   0,                                    /* @tp_iter@ */
1437   0,                                    /* @tp_iternext@ */
1438   0,                                    /* @tp_methods@ */
1439   0,                                    /* @tp_members@ */
1440   gcaead_pygetset,                      /* @tp_getset@ */
1441   0,                                    /* @tp_base@ */
1442   0,                                    /* @tp_dict@ */
1443   0,                                    /* @tp_descr_get@ */
1444   0,                                    /* @tp_descr_set@ */
1445   0,                                    /* @tp_dictoffset@ */
1446   0,                                    /* @tp_init@ */
1447   PyType_GenericAlloc,                  /* @tp_alloc@ */
1448   abstract_pynew,                       /* @tp_new@ */
1449   0,                                    /* @tp_free@ */
1450   0                                     /* @tp_is_gc@ */
1451 };
1452
1453 static PyTypeObject gaeadkey_pytype_skel = {
1454   PyObject_HEAD_INIT(0) 0,              /* Header */
1455   "GAEKey",                             /* @tp_name@ */
1456   sizeof(gaeadkey_pyobj),               /* @tp_basicsize@ */
1457   0,                                    /* @tp_itemsize@ */
1458
1459   gaeadkey_pydealloc,                   /* @tp_dealloc@ */
1460   0,                                    /* @tp_print@ */
1461   0,                                    /* @tp_getattr@ */
1462   0,                                    /* @tp_setattr@ */
1463   0,                                    /* @tp_compare@ */
1464   0,                                    /* @tp_repr@ */
1465   0,                                    /* @tp_as_number@ */
1466   0,                                    /* @tp_as_sequence@ */
1467   0,                                    /* @tp_as_mapping@ */
1468   0,                                    /* @tp_hash@ */
1469   0,                                    /* @tp_call@ */
1470   0,                                    /* @tp_str@ */
1471   0,                                    /* @tp_getattro@ */
1472   0,                                    /* @tp_setattro@ */
1473   0,                                    /* @tp_as_buffer@ */
1474   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1475     Py_TPFLAGS_BASETYPE,
1476
1477   /* @tp_doc@ */
1478 "Authenticated encryption key.",
1479
1480   0,                                    /* @tp_traverse@ */
1481   0,                                    /* @tp_clear@ */
1482   0,                                    /* @tp_richcompare@ */
1483   0,                                    /* @tp_weaklistoffset@ */
1484   0,                                    /* @tp_iter@ */
1485   0,                                    /* @tp_iternext@ */
1486   gaeadkey_pymethods,                   /* @tp_methods@ */
1487   0,                                    /* @tp_members@ */
1488   0,                                    /* @tp_getset@ */
1489   0,                                    /* @tp_base@ */
1490   0,                                    /* @tp_dict@ */
1491   0,                                    /* @tp_descr_get@ */
1492   0,                                    /* @tp_descr_set@ */
1493   0,                                    /* @tp_dictoffset@ */
1494   0,                                    /* @tp_init@ */
1495   PyType_GenericAlloc,                  /* @tp_alloc@ */
1496   abstract_pynew,                       /* @tp_new@ */
1497   0,                                    /* @tp_free@ */
1498   0                                     /* @tp_is_gc@ */
1499 };
1500
1501 static PyTypeObject gcaeadaad_pytype_skel = {
1502   PyObject_HEAD_INIT(0) 0,              /* Header */
1503   "GAEAADClass",                        /* @tp_name@ */
1504   sizeof(gcaeadaad_pyobj),              /* @tp_basicsize@ */
1505   0,                                    /* @tp_itemsize@ */
1506
1507   0,                                    /* @tp_dealloc@ */
1508   0,                                    /* @tp_print@ */
1509   0,                                    /* @tp_getattr@ */
1510   0,                                    /* @tp_setattr@ */
1511   0,                                    /* @tp_compare@ */
1512   0,                                    /* @tp_repr@ */
1513   0,                                    /* @tp_as_number@ */
1514   0,                                    /* @tp_as_sequence@ */
1515   0,                                    /* @tp_as_mapping@ */
1516   0,                                    /* @tp_hash@ */
1517   0,                                    /* @tp_call@ */
1518   0,                                    /* @tp_str@ */
1519   0,                                    /* @tp_getattro@ */
1520   0,                                    /* @tp_setattro@ */
1521   0,                                    /* @tp_as_buffer@ */
1522   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1523     Py_TPFLAGS_BASETYPE,
1524
1525   /* @tp_doc@ */
1526 "Authenticated encryption additional-data hash metaclass.",
1527
1528   0,                                    /* @tp_traverse@ */
1529   0,                                    /* @tp_clear@ */
1530   0,                                    /* @tp_richcompare@ */
1531   0,                                    /* @tp_weaklistoffset@ */
1532   0,                                    /* @tp_iter@ */
1533   0,                                    /* @tp_iternext@ */
1534   0,                                    /* @tp_methods@ */
1535   0,                                    /* @tp_members@ */
1536   0,                                    /* @tp_getset@ */
1537   0,                                    /* @tp_base@ */
1538   0,                                    /* @tp_dict@ */
1539   0,                                    /* @tp_descr_get@ */
1540   0,                                    /* @tp_descr_set@ */
1541   0,                                    /* @tp_dictoffset@ */
1542   0,                                    /* @tp_init@ */
1543   PyType_GenericAlloc,                  /* @tp_alloc@ */
1544   abstract_pynew,                       /* @tp_new@ */
1545   0,                                    /* @tp_free@ */
1546   0                                     /* @tp_is_gc@ */
1547 };
1548
1549 static PyTypeObject gaeadaad_pytype_skel = {
1550   PyObject_HEAD_INIT(0) 0,              /* Header */
1551   "GAEAAD",                             /* @tp_name@ */
1552   sizeof(gaeadaad_pyobj),               /* @tp_basicsize@ */
1553   0,                                    /* @tp_itemsize@ */
1554
1555   gaeadaad_pydealloc,                   /* @tp_dealloc@ */
1556   0,                                    /* @tp_print@ */
1557   0,                                    /* @tp_getattr@ */
1558   0,                                    /* @tp_setattr@ */
1559   0,                                    /* @tp_compare@ */
1560   0,                                    /* @tp_repr@ */
1561   0,                                    /* @tp_as_number@ */
1562   0,                                    /* @tp_as_sequence@ */
1563   0,                                    /* @tp_as_mapping@ */
1564   0,                                    /* @tp_hash@ */
1565   0,                                    /* @tp_call@ */
1566   0,                                    /* @tp_str@ */
1567   0,                                    /* @tp_getattro@ */
1568   0,                                    /* @tp_setattro@ */
1569   0,                                    /* @tp_as_buffer@ */
1570   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1571     Py_TPFLAGS_BASETYPE,
1572
1573   /* @tp_doc@ */
1574 "Authenticated encryption AAD hash.",
1575
1576   0,                                    /* @tp_traverse@ */
1577   0,                                    /* @tp_clear@ */
1578   0,                                    /* @tp_richcompare@ */
1579   0,                                    /* @tp_weaklistoffset@ */
1580   0,                                    /* @tp_iter@ */
1581   0,                                    /* @tp_iternext@ */
1582   gaeadaad_pymethods,                   /* @tp_methods@ */
1583   0,                                    /* @tp_members@ */
1584   gaeadaad_pygetset,                    /* @tp_getset@ */
1585   0,                                    /* @tp_base@ */
1586   0,                                    /* @tp_dict@ */
1587   0,                                    /* @tp_descr_get@ */
1588   0,                                    /* @tp_descr_set@ */
1589   0,                                    /* @tp_dictoffset@ */
1590   0,                                    /* @tp_init@ */
1591   PyType_GenericAlloc,                  /* @tp_alloc@ */
1592   abstract_pynew,                       /* @tp_new@ */
1593   0,                                    /* @tp_free@ */
1594   0                                     /* @tp_is_gc@ */
1595 };
1596
1597 static PyTypeObject gcaeadenc_pytype_skel = {
1598   PyObject_HEAD_INIT(0) 0,              /* Header */
1599   "GAEEncClass",                        /* @tp_name@ */
1600   sizeof(gcaeadenc_pyobj),              /* @tp_basicsize@ */
1601   0,                                    /* @tp_itemsize@ */
1602
1603   0,                                    /* @tp_dealloc@ */
1604   0,                                    /* @tp_print@ */
1605   0,                                    /* @tp_getattr@ */
1606   0,                                    /* @tp_setattr@ */
1607   0,                                    /* @tp_compare@ */
1608   0,                                    /* @tp_repr@ */
1609   0,                                    /* @tp_as_number@ */
1610   0,                                    /* @tp_as_sequence@ */
1611   0,                                    /* @tp_as_mapping@ */
1612   0,                                    /* @tp_hash@ */
1613   0,                                    /* @tp_call@ */
1614   0,                                    /* @tp_str@ */
1615   0,                                    /* @tp_getattro@ */
1616   0,                                    /* @tp_setattro@ */
1617   0,                                    /* @tp_as_buffer@ */
1618   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1619     Py_TPFLAGS_BASETYPE,
1620
1621   /* @tp_doc@ */
1622 "Authenticated encryption operation metaclass.",
1623
1624   0,                                    /* @tp_traverse@ */
1625   0,                                    /* @tp_clear@ */
1626   0,                                    /* @tp_richcompare@ */
1627   0,                                    /* @tp_weaklistoffset@ */
1628   0,                                    /* @tp_iter@ */
1629   0,                                    /* @tp_iternext@ */
1630   0,                                    /* @tp_methods@ */
1631   0,                                    /* @tp_members@ */
1632   0,                                    /* @tp_getset@ */
1633   0,                                    /* @tp_base@ */
1634   0,                                    /* @tp_dict@ */
1635   0,                                    /* @tp_descr_get@ */
1636   0,                                    /* @tp_descr_set@ */
1637   0,                                    /* @tp_dictoffset@ */
1638   0,                                    /* @tp_init@ */
1639   PyType_GenericAlloc,                  /* @tp_alloc@ */
1640   abstract_pynew,                       /* @tp_new@ */
1641   0,                                    /* @tp_free@ */
1642   0                                     /* @tp_is_gc@ */
1643 };
1644
1645 static PyTypeObject gaeadenc_pytype_skel = {
1646   PyObject_HEAD_INIT(0) 0,              /* Header */
1647   "GAEEnc",                             /* @tp_name@ */
1648   sizeof(gaeadenc_pyobj),               /* @tp_basicsize@ */
1649   0,                                    /* @tp_itemsize@ */
1650
1651   gaeadenc_pydealloc,                   /* @tp_dealloc@ */
1652   0,                                    /* @tp_print@ */
1653   0,                                    /* @tp_getattr@ */
1654   0,                                    /* @tp_setattr@ */
1655   0,                                    /* @tp_compare@ */
1656   0,                                    /* @tp_repr@ */
1657   0,                                    /* @tp_as_number@ */
1658   0,                                    /* @tp_as_sequence@ */
1659   0,                                    /* @tp_as_mapping@ */
1660   0,                                    /* @tp_hash@ */
1661   0,                                    /* @tp_call@ */
1662   0,                                    /* @tp_str@ */
1663   0,                                    /* @tp_getattro@ */
1664   0,                                    /* @tp_setattro@ */
1665   0,                                    /* @tp_as_buffer@ */
1666   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1667     Py_TPFLAGS_BASETYPE,
1668
1669   /* @tp_doc@ */
1670 "Authenticated encryption operation.",
1671
1672   0,                                    /* @tp_traverse@ */
1673   0,                                    /* @tp_clear@ */
1674   0,                                    /* @tp_richcompare@ */
1675   0,                                    /* @tp_weaklistoffset@ */
1676   0,                                    /* @tp_iter@ */
1677   0,                                    /* @tp_iternext@ */
1678   gaeadenc_pymethods,                   /* @tp_methods@ */
1679   0,                                    /* @tp_members@ */
1680   gaeadenc_pygetset,                    /* @tp_getset@ */
1681   0,                                    /* @tp_base@ */
1682   0,                                    /* @tp_dict@ */
1683   0,                                    /* @tp_descr_get@ */
1684   0,                                    /* @tp_descr_set@ */
1685   0,                                    /* @tp_dictoffset@ */
1686   0,                                    /* @tp_init@ */
1687   PyType_GenericAlloc,                  /* @tp_alloc@ */
1688   abstract_pynew,                       /* @tp_new@ */
1689   0,                                    /* @tp_free@ */
1690   0                                     /* @tp_is_gc@ */
1691 };
1692
1693 static PyTypeObject gcaeaddec_pytype_skel = {
1694   PyObject_HEAD_INIT(0) 0,              /* Header */
1695   "GAEDecClass",                        /* @tp_name@ */
1696   sizeof(gcaeaddec_pyobj),              /* @tp_basicsize@ */
1697   0,                                    /* @tp_itemsize@ */
1698
1699   0,                                    /* @tp_dealloc@ */
1700   0,                                    /* @tp_print@ */
1701   0,                                    /* @tp_getattr@ */
1702   0,                                    /* @tp_setattr@ */
1703   0,                                    /* @tp_compare@ */
1704   0,                                    /* @tp_repr@ */
1705   0,                                    /* @tp_as_number@ */
1706   0,                                    /* @tp_as_sequence@ */
1707   0,                                    /* @tp_as_mapping@ */
1708   0,                                    /* @tp_hash@ */
1709   0,                                    /* @tp_call@ */
1710   0,                                    /* @tp_str@ */
1711   0,                                    /* @tp_getattro@ */
1712   0,                                    /* @tp_setattro@ */
1713   0,                                    /* @tp_as_buffer@ */
1714   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1715     Py_TPFLAGS_BASETYPE,
1716
1717   /* @tp_doc@ */
1718 "Authenticated decryption operation metaclass.",
1719
1720   0,                                    /* @tp_traverse@ */
1721   0,                                    /* @tp_clear@ */
1722   0,                                    /* @tp_richcompare@ */
1723   0,                                    /* @tp_weaklistoffset@ */
1724   0,                                    /* @tp_iter@ */
1725   0,                                    /* @tp_iternext@ */
1726   0,                                    /* @tp_methods@ */
1727   0,                                    /* @tp_members@ */
1728   0,                                    /* @tp_getset@ */
1729   0,                                    /* @tp_base@ */
1730   0,                                    /* @tp_dict@ */
1731   0,                                    /* @tp_descr_get@ */
1732   0,                                    /* @tp_descr_set@ */
1733   0,                                    /* @tp_dictoffset@ */
1734   0,                                    /* @tp_init@ */
1735   PyType_GenericAlloc,                  /* @tp_alloc@ */
1736   abstract_pynew,                       /* @tp_new@ */
1737   0,                                    /* @tp_free@ */
1738   0                                     /* @tp_is_gc@ */
1739 };
1740
1741 static PyTypeObject gaeaddec_pytype_skel = {
1742   PyObject_HEAD_INIT(0) 0,              /* Header */
1743   "GAEDec",                             /* @tp_name@ */
1744   sizeof(gaeaddec_pyobj),               /* @tp_basicsize@ */
1745   0,                                    /* @tp_itemsize@ */
1746
1747   gaeaddec_pydealloc,                   /* @tp_dealloc@ */
1748   0,                                    /* @tp_print@ */
1749   0,                                    /* @tp_getattr@ */
1750   0,                                    /* @tp_setattr@ */
1751   0,                                    /* @tp_compare@ */
1752   0,                                    /* @tp_repr@ */
1753   0,                                    /* @tp_as_number@ */
1754   0,                                    /* @tp_as_sequence@ */
1755   0,                                    /* @tp_as_mapping@ */
1756   0,                                    /* @tp_hash@ */
1757   0,                                    /* @tp_call@ */
1758   0,                                    /* @tp_str@ */
1759   0,                                    /* @tp_getattro@ */
1760   0,                                    /* @tp_setattro@ */
1761   0,                                    /* @tp_as_buffer@ */
1762   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1763     Py_TPFLAGS_BASETYPE,
1764
1765   /* @tp_doc@ */
1766 "Authenticated decryption operation.",
1767
1768   0,                                    /* @tp_traverse@ */
1769   0,                                    /* @tp_clear@ */
1770   0,                                    /* @tp_richcompare@ */
1771   0,                                    /* @tp_weaklistoffset@ */
1772   0,                                    /* @tp_iter@ */
1773   0,                                    /* @tp_iternext@ */
1774   gaeaddec_pymethods,                   /* @tp_methods@ */
1775   0,                                    /* @tp_members@ */
1776   gaeaddec_pygetset,                    /* @tp_getset@ */
1777   0,                                    /* @tp_base@ */
1778   0,                                    /* @tp_dict@ */
1779   0,                                    /* @tp_descr_get@ */
1780   0,                                    /* @tp_descr_set@ */
1781   0,                                    /* @tp_dictoffset@ */
1782   0,                                    /* @tp_init@ */
1783   PyType_GenericAlloc,                  /* @tp_alloc@ */
1784   abstract_pynew,                       /* @tp_new@ */
1785   0,                                    /* @tp_free@ */
1786   0                                     /* @tp_is_gc@ */
1787 };
1788
1789 /*----- Hash functions ----------------------------------------------------*/
1790
1791 PyTypeObject *gchash_pytype, *ghash_pytype;
1792
1793 CONVFUNC(gchash, gchash *, GCHASH_CH)
1794 CONVFUNC(ghash, ghash *, GHASH_H)
1795
1796 static PyObject *ghash_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1797 {
1798   static const char *const kwlist[] = { 0 };
1799   if (!PyArg_ParseTupleAndKeywords(arg, kw, ":new", KWLIST))
1800     goto end;
1801   return (ghash_pywrap((PyObject *)ty, GH_INIT(GCHASH_CH(ty))));
1802 end:
1803   return (0);
1804 }
1805
1806 PyObject *gchash_pywrap(gchash *ch)
1807 {
1808   gchash_pyobj *g = newtype(gchash_pytype, 0, ch->name);
1809   g->ch = ch;
1810   g->ty.ht_type.tp_basicsize = sizeof(ghash_pyobj);
1811   g->ty.ht_type.tp_base = ghash_pytype;
1812   Py_INCREF(ghash_pytype);
1813   g->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
1814                             Py_TPFLAGS_BASETYPE |
1815                             Py_TPFLAGS_HEAPTYPE);
1816   g->ty.ht_type.tp_alloc = PyType_GenericAlloc;
1817   g->ty.ht_type.tp_free = 0;
1818   g->ty.ht_type.tp_new = ghash_pynew;
1819   typeready(&g->ty.ht_type);
1820   return ((PyObject *)g);
1821 }
1822
1823 PyObject *ghash_pywrap(PyObject *cobj, ghash *h)
1824 {
1825   ghash_pyobj *g;
1826   if (!cobj) cobj = gchash_pywrap((/*unconst*/ gchash *)GH_CLASS(h));
1827   else Py_INCREF(cobj);
1828   g = PyObject_NEW(ghash_pyobj, (PyTypeObject *)cobj);
1829   g->h = h;
1830   return ((PyObject *)g);
1831 }
1832
1833 static void ghash_pydealloc(PyObject *me)
1834 {
1835   GH_DESTROY(GHASH_H(me));
1836   Py_DECREF(me->ob_type);
1837   FREEOBJ(me);
1838 }
1839
1840 static PyObject *gchget_name(PyObject *me, void *hunoz)
1841   { return (PyString_FromString(GCHASH_CH(me)->name)); }
1842
1843 static PyObject *gchget_hashsz(PyObject *me, void *hunoz)
1844   { return (PyInt_FromLong(GCHASH_CH(me)->hashsz)); }
1845
1846 static PyObject *gchget_bufsz(PyObject *me, void *hunoz)
1847   { return (PyInt_FromLong(GCHASH_CH(me)->bufsz)); }
1848
1849 static PyObject *ghmeth_copy(PyObject *me, PyObject *arg)
1850 {
1851   if (!PyArg_ParseTuple(arg, ":copy")) return (0);
1852   return (ghash_pywrap((PyObject *)me->ob_type, GH_COPY(GHASH_H(me))));
1853 }
1854
1855 static PyObject *ghmeth_hash(PyObject *me, PyObject *arg)
1856 {
1857   char *p;
1858   Py_ssize_t sz;
1859   if (!PyArg_ParseTuple(arg, "s#:hash", &p, &sz)) return (0);
1860   GH_HASH(GHASH_H(me), p, sz);
1861   RETURN_ME;
1862 }
1863
1864 #define GHMETH_HASHU_(n, W, w)                                          \
1865   static PyObject *ghmeth_hashu##w(PyObject *me, PyObject *arg)         \
1866   {                                                                     \
1867     uint##n x;                                                          \
1868     if (!PyArg_ParseTuple(arg, "O&:hashu" #w, convu##n, &x)) return (0); \
1869     GH_HASHU##W(GHASH_H(me), x);                                        \
1870     RETURN_ME;                                                          \
1871   }
1872 DOUINTCONV(GHMETH_HASHU_)
1873
1874 #define GHMETH_HASHBUF_(n, W, w)                                        \
1875   static PyObject *ghmeth_hashbuf##w(PyObject *me, PyObject *arg)       \
1876   {                                                                     \
1877     char *p;                                                            \
1878     Py_ssize_t sz;                                                      \
1879     if (!PyArg_ParseTuple(arg, "s#:hashbuf" #w, &p, &sz)) goto end;     \
1880     if (sz > MASK##n) TYERR("string too long");                         \
1881     GH_HASHBUF##W(GHASH_H(me), p, sz);                                  \
1882     RETURN_ME;                                                          \
1883   end:                                                                  \
1884     return (0);                                                         \
1885   }
1886 DOUINTCONV(GHMETH_HASHBUF_)
1887
1888 static PyObject *ghmeth_hashstrz(PyObject *me, PyObject *arg)
1889 {
1890   char *p;
1891   if (!PyArg_ParseTuple(arg, "s:hashstrz", &p)) return (0);
1892   GH_HASHSTRZ(GHASH_H(me), p);
1893   RETURN_ME;
1894 }
1895
1896 static PyObject *ghmeth_done(PyObject *me, PyObject *arg)
1897 {
1898   ghash *g;
1899   PyObject *rc;
1900   if (!PyArg_ParseTuple(arg, ":done")) return (0);
1901   g = GH_COPY(GHASH_H(me));
1902   rc = bytestring_pywrap(0, g->ops->c->hashsz);
1903   GH_DONE(g, PyString_AS_STRING(rc));
1904   GH_DESTROY(g);
1905   return (rc);
1906 }
1907
1908 static PyGetSetDef gchash_pygetset[] = {
1909 #define GETSETNAME(op, name) gch##op##_##name
1910   GET   (bufsz,                 "CH.bufsz -> hash buffer size, or zero")
1911   GET   (hashsz,                "CH.hashsz -> hash output size")
1912   GET   (name,                  "CH.name -> name of this kind of hash")
1913 #undef GETSETNAME
1914   { 0 }
1915 };
1916
1917 static PyMethodDef ghash_pymethods[] = {
1918 #define METHNAME(name) ghmeth_##name
1919   METH  (copy,                  "H.copy() -> HH")
1920   METH  (hash,                  "H.hash(M)")
1921 #define METHU_(n, W, w) METH(hashu##w, "H.hashu" #w "(WORD)")
1922   DOUINTCONV(METHU_)
1923 #undef METHU_
1924 #define METHBUF_(n, W, w) METH(hashbuf##w, "H.hashbuf" #w "(BYTES)")
1925   DOUINTCONV(METHBUF_)
1926 #undef METHBUF_
1927   METH  (hashstrz,              "H.hashstrz(STRING)")
1928   METH  (done,                  "H.done() -> HASH")
1929 #undef METHNAME
1930   { 0 }
1931 };
1932
1933 static PyTypeObject gchash_pytype_skel = {
1934   PyObject_HEAD_INIT(0) 0,              /* Header */
1935   "GCHash",                             /* @tp_name@ */
1936   sizeof(gchash_pyobj),                 /* @tp_basicsize@ */
1937   0,                                    /* @tp_itemsize@ */
1938
1939   0,                                    /* @tp_dealloc@ */
1940   0,                                    /* @tp_print@ */
1941   0,                                    /* @tp_getattr@ */
1942   0,                                    /* @tp_setattr@ */
1943   0,                                    /* @tp_compare@ */
1944   0,                                    /* @tp_repr@ */
1945   0,                                    /* @tp_as_number@ */
1946   0,                                    /* @tp_as_sequence@ */
1947   0,                                    /* @tp_as_mapping@ */
1948   0,                                    /* @tp_hash@ */
1949   0,                                    /* @tp_call@ */
1950   0,                                    /* @tp_str@ */
1951   0,                                    /* @tp_getattro@ */
1952   0,                                    /* @tp_setattro@ */
1953   0,                                    /* @tp_as_buffer@ */
1954   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1955     Py_TPFLAGS_BASETYPE,
1956
1957   /* @tp_doc@ */
1958 "Hash function metaclass.",
1959
1960   0,                                    /* @tp_traverse@ */
1961   0,                                    /* @tp_clear@ */
1962   0,                                    /* @tp_richcompare@ */
1963   0,                                    /* @tp_weaklistoffset@ */
1964   0,                                    /* @tp_iter@ */
1965   0,                                    /* @tp_iternext@ */
1966   0,                                    /* @tp_methods@ */
1967   0,                                    /* @tp_members@ */
1968   gchash_pygetset,                      /* @tp_getset@ */
1969   0,                                    /* @tp_base@ */
1970   0,                                    /* @tp_dict@ */
1971   0,                                    /* @tp_descr_get@ */
1972   0,                                    /* @tp_descr_set@ */
1973   0,                                    /* @tp_dictoffset@ */
1974   0,                                    /* @tp_init@ */
1975   PyType_GenericAlloc,                  /* @tp_alloc@ */
1976   abstract_pynew,                       /* @tp_new@ */
1977   0,                                    /* @tp_free@ */
1978   0                                     /* @tp_is_gc@ */
1979 };
1980
1981 static PyTypeObject ghash_pytype_skel = {
1982   PyObject_HEAD_INIT(0) 0,              /* Header */
1983   "GHash",                              /* @tp_name@ */
1984   sizeof(ghash_pyobj),                  /* @tp_basicsize@ */
1985   0,                                    /* @tp_itemsize@ */
1986
1987   ghash_pydealloc,                      /* @tp_dealloc@ */
1988   0,                                    /* @tp_print@ */
1989   0,                                    /* @tp_getattr@ */
1990   0,                                    /* @tp_setattr@ */
1991   0,                                    /* @tp_compare@ */
1992   0,                                    /* @tp_repr@ */
1993   0,                                    /* @tp_as_number@ */
1994   0,                                    /* @tp_as_sequence@ */
1995   0,                                    /* @tp_as_mapping@ */
1996   0,                                    /* @tp_hash@ */
1997   0,                                    /* @tp_call@ */
1998   0,                                    /* @tp_str@ */
1999   0,                                    /* @tp_getattro@ */
2000   0,                                    /* @tp_setattro@ */
2001   0,                                    /* @tp_as_buffer@ */
2002   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2003     Py_TPFLAGS_BASETYPE,
2004
2005   /* @tp_doc@ */
2006 "Hash function, abstract base class.",
2007
2008   0,                                    /* @tp_traverse@ */
2009   0,                                    /* @tp_clear@ */
2010   0,                                    /* @tp_richcompare@ */
2011   0,                                    /* @tp_weaklistoffset@ */
2012   0,                                    /* @tp_iter@ */
2013   0,                                    /* @tp_iternext@ */
2014   ghash_pymethods,                      /* @tp_methods@ */
2015   0,                                    /* @tp_members@ */
2016   0,                                    /* @tp_getset@ */
2017   0,                                    /* @tp_base@ */
2018   0,                                    /* @tp_dict@ */
2019   0,                                    /* @tp_descr_get@ */
2020   0,                                    /* @tp_descr_set@ */
2021   0,                                    /* @tp_dictoffset@ */
2022   0,                                    /* @tp_init@ */
2023   PyType_GenericAlloc,                  /* @tp_alloc@ */
2024   abstract_pynew,                       /* @tp_new@ */
2025   0,                                    /* @tp_free@ */
2026   0                                     /* @tp_is_gc@ */
2027 };
2028
2029 /*----- Message authentication --------------------------------------------*/
2030
2031 PyTypeObject *gcmac_pytype, *gmac_pytype, *gmhash_pytype;
2032
2033 CONVFUNC(gcmac, gcmac *, GCMAC_CM)
2034 CONVFUNC(gmac, gmac *, GMAC_M)
2035 CONVFUNC(gmhash, ghash *, GHASH_H)
2036
2037 static PyObject *gmac_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
2038 {
2039   static const char *const kwlist[] = { "k", 0 };
2040   char *k;
2041   Py_ssize_t sz;
2042
2043   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#:new", KWLIST, &k, &sz))
2044     goto end;
2045   if (keysz(sz, GCMAC_CM(ty)->keysz) != sz) VALERR("bad key length");
2046   return (gmac_pywrap((PyObject *)ty,
2047                       GM_KEY(GCMAC_CM(ty), k, sz)));
2048 end:
2049   return (0);
2050 }
2051
2052 static PyObject *gmhash_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
2053 {
2054   static const char *const kwlist[] = { 0 };
2055   ghash_pyobj *g;
2056
2057   if (!PyArg_ParseTupleAndKeywords(arg, kw, ":new", KWLIST)) return (0);
2058   g = PyObject_NEW(ghash_pyobj, ty);
2059   g->h = GM_INIT(GMAC_M(ty));
2060   Py_INCREF(ty);
2061   return ((PyObject *)g);
2062 }
2063
2064 PyObject *gcmac_pywrap(gcmac *cm)
2065 {
2066   gcmac_pyobj *g = newtype(gcmac_pytype, 0, cm->name);
2067   g->cm = cm;
2068   g->ty.ht_type.tp_basicsize = sizeof(gmac_pyobj);
2069   g->ty.ht_type.tp_base = gmac_pytype;
2070   Py_INCREF(gmac_pytype);
2071   g->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
2072                             Py_TPFLAGS_BASETYPE |
2073                             Py_TPFLAGS_HEAPTYPE);
2074   g->ty.ht_type.tp_alloc = PyType_GenericAlloc;
2075   g->ty.ht_type.tp_free = 0;
2076   g->ty.ht_type.tp_new = gmac_pynew;
2077   typeready(&g->ty.ht_type);
2078   return ((PyObject *)g);
2079 }
2080
2081 PyObject *gmac_pywrap(PyObject *cobj, gmac *m)
2082 {
2083   gmac_pyobj *g;
2084   if (!cobj) cobj = gcmac_pywrap((/*unconst*/ gcmac *)GM_CLASS(m));
2085   else Py_INCREF(cobj);
2086   g = newtype((PyTypeObject *)cobj, 0, 0);
2087   g->ty.ht_type.tp_basicsize = sizeof(ghash_pyobj);
2088   g->ty.ht_name = PyString_FromFormat("%s(keyed)", m->ops->c->name);
2089   g->ty.ht_type.tp_name = PyString_AS_STRING(g->ty.ht_name);
2090   g->ty.ht_type.tp_base = gmhash_pytype;
2091   Py_INCREF(gmac_pytype);
2092   g->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
2093                             Py_TPFLAGS_BASETYPE |
2094                             Py_TPFLAGS_HEAPTYPE);
2095   g->ty.ht_type.tp_alloc = PyType_GenericAlloc;
2096   g->ty.ht_type.tp_free = 0;
2097   g->ty.ht_type.tp_new = gmhash_pynew;
2098   typeready(&g->ty.ht_type);
2099   g->m = m;
2100   return ((PyObject *)g);
2101 }
2102
2103 static void gmac_pydealloc(PyObject *me)
2104 {
2105   GM_DESTROY(GMAC_M(me));
2106   Py_DECREF(me->ob_type);
2107   PyType_Type.tp_dealloc(me);
2108 }
2109
2110 static PyObject *gcmget_name(PyObject *me, void *hunoz)
2111   { return (PyString_FromString(GCMAC_CM(me)->name)); }
2112
2113 static PyObject *gcmget_keysz(PyObject *me, void *hunoz)
2114   { return (keysz_pywrap(GCMAC_CM(me)->keysz)); }
2115
2116 static PyObject *gcmget_tagsz(PyObject *me, void *hunoz)
2117   { return (PyInt_FromLong(GCMAC_CM(me)->hashsz)); }
2118
2119 static PyGetSetDef gcmac_pygetset[] = {
2120 #define GETSETNAME(op, name) gcm##op##_##name
2121   GET   (keysz,                 "CM.keysz -> acceptable key sizes")
2122   GET   (tagsz,                 "CM.tagsz -> MAC output size")
2123   GET   (name,                  "CM.name -> name of this kind of MAC")
2124 #undef GETSETNAME
2125   { 0 }
2126 };
2127
2128 static PyTypeObject gcmac_pytype_skel = {
2129   PyObject_HEAD_INIT(0) 0,              /* Header */
2130   "GCMAC",                              /* @tp_name@ */
2131   sizeof(gchash_pyobj),                 /* @tp_basicsize@ */
2132   0,                                    /* @tp_itemsize@ */
2133
2134   0,                                    /* @tp_dealloc@ */
2135   0,                                    /* @tp_print@ */
2136   0,                                    /* @tp_getattr@ */
2137   0,                                    /* @tp_setattr@ */
2138   0,                                    /* @tp_compare@ */
2139   0,                                    /* @tp_repr@ */
2140   0,                                    /* @tp_as_number@ */
2141   0,                                    /* @tp_as_sequence@ */
2142   0,                                    /* @tp_as_mapping@ */
2143   0,                                    /* @tp_hash@ */
2144   0,                                    /* @tp_call@ */
2145   0,                                    /* @tp_str@ */
2146   0,                                    /* @tp_getattro@ */
2147   0,                                    /* @tp_setattro@ */
2148   0,                                    /* @tp_as_buffer@ */
2149   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2150     Py_TPFLAGS_BASETYPE,
2151
2152   /* @tp_doc@ */
2153 "Message authentication code metametaclass.",
2154
2155   0,                                    /* @tp_traverse@ */
2156   0,                                    /* @tp_clear@ */
2157   0,                                    /* @tp_richcompare@ */
2158   0,                                    /* @tp_weaklistoffset@ */
2159   0,                                    /* @tp_iter@ */
2160   0,                                    /* @tp_iternext@ */
2161   0,                                    /* @tp_methods@ */
2162   0,                                    /* @tp_members@ */
2163   gcmac_pygetset,                       /* @tp_getset@ */
2164   0,                                    /* @tp_base@ */
2165   0,                                    /* @tp_dict@ */
2166   0,                                    /* @tp_descr_get@ */
2167   0,                                    /* @tp_descr_set@ */
2168   0,                                    /* @tp_dictoffset@ */
2169   0,                                    /* @tp_init@ */
2170   PyType_GenericAlloc,                  /* @tp_alloc@ */
2171   abstract_pynew,                       /* @tp_new@ */
2172   0,                                    /* @tp_free@ */
2173   0                                     /* @tp_is_gc@ */
2174 };
2175
2176 static PyTypeObject gmac_pytype_skel = {
2177   PyObject_HEAD_INIT(0) 0,              /* Header */
2178   "GMAC",                               /* @tp_name@ */
2179   sizeof(gmac_pyobj),                   /* @tp_basicsize@ */
2180   0,                                    /* @tp_itemsize@ */
2181
2182   gmac_pydealloc,                       /* @tp_dealloc@ */
2183   0,                                    /* @tp_print@ */
2184   0,                                    /* @tp_getattr@ */
2185   0,                                    /* @tp_setattr@ */
2186   0,                                    /* @tp_compare@ */
2187   0,                                    /* @tp_repr@ */
2188   0,                                    /* @tp_as_number@ */
2189   0,                                    /* @tp_as_sequence@ */
2190   0,                                    /* @tp_as_mapping@ */
2191   0,                                    /* @tp_hash@ */
2192   0,                                    /* @tp_call@ */
2193   0,                                    /* @tp_str@ */
2194   0,                                    /* @tp_getattro@ */
2195   0,                                    /* @tp_setattro@ */
2196   0,                                    /* @tp_as_buffer@ */
2197   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2198     Py_TPFLAGS_BASETYPE,
2199
2200   /* @tp_doc@ */
2201 "Message authentication code metaclass, abstract base class.",
2202
2203   0,                                    /* @tp_traverse@ */
2204   0,                                    /* @tp_clear@ */
2205   0,                                    /* @tp_richcompare@ */
2206   0,                                    /* @tp_weaklistoffset@ */
2207   0,                                    /* @tp_iter@ */
2208   0,                                    /* @tp_iternext@ */
2209   0,                                    /* @tp_methods@ */
2210   0,                                    /* @tp_members@ */
2211   0,                                    /* @tp_getset@ */
2212   0,                                    /* @tp_base@ */
2213   0,                                    /* @tp_dict@ */
2214   0,                                    /* @tp_descr_get@ */
2215   0,                                    /* @tp_descr_set@ */
2216   0,                                    /* @tp_dictoffset@ */
2217   0,                                    /* @tp_init@ */
2218   PyType_GenericAlloc,                  /* @tp_alloc@ */
2219   abstract_pynew,                       /* @tp_new@ */
2220   0,                                    /* @tp_free@ */
2221   0                                     /* @tp_is_gc@ */
2222 };
2223
2224 static PyTypeObject gmhash_pytype_skel = {
2225   PyObject_HEAD_INIT(0) 0,              /* Header */
2226   "GMACHash",                           /* @tp_name@ */
2227   sizeof(ghash_pyobj),                  /* @tp_basicsize@ */
2228   0,                                    /* @tp_itemsize@ */
2229
2230   ghash_pydealloc,                      /* @tp_dealloc@ */
2231   0,                                    /* @tp_print@ */
2232   0,                                    /* @tp_getattr@ */
2233   0,                                    /* @tp_setattr@ */
2234   0,                                    /* @tp_compare@ */
2235   0,                                    /* @tp_repr@ */
2236   0,                                    /* @tp_as_number@ */
2237   0,                                    /* @tp_as_sequence@ */
2238   0,                                    /* @tp_as_mapping@ */
2239   0,                                    /* @tp_hash@ */
2240   0,                                    /* @tp_call@ */
2241   0,                                    /* @tp_str@ */
2242   0,                                    /* @tp_getattro@ */
2243   0,                                    /* @tp_setattro@ */
2244   0,                                    /* @tp_as_buffer@ */
2245   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2246     Py_TPFLAGS_BASETYPE,
2247
2248   /* @tp_doc@ */
2249 "Message authentication code, abstract base class.",
2250
2251   0,                                    /* @tp_traverse@ */
2252   0,                                    /* @tp_clear@ */
2253   0,                                    /* @tp_richcompare@ */
2254   0,                                    /* @tp_weaklistoffset@ */
2255   0,                                    /* @tp_iter@ */
2256   0,                                    /* @tp_iternext@ */
2257   0,                                    /* @tp_methods@ */
2258   0,                                    /* @tp_members@ */
2259   0,                                    /* @tp_getset@ */
2260   0,                                    /* @tp_base@ */
2261   0,                                    /* @tp_dict@ */
2262   0,                                    /* @tp_descr_get@ */
2263   0,                                    /* @tp_descr_set@ */
2264   0,                                    /* @tp_dictoffset@ */
2265   0,                                    /* @tp_init@ */
2266   PyType_GenericAlloc,                  /* @tp_alloc@ */
2267   abstract_pynew,                       /* @tp_new@ */
2268   0,                                    /* @tp_free@ */
2269   0                                     /* @tp_is_gc@ */
2270 };
2271
2272 /*----- Special snowflake for Poly1305 ------------------------------------*/
2273
2274 PyTypeObject *poly1305cls_pytype, *poly1305key_pytype, *poly1305hash_pytype;
2275
2276 typedef struct poly1305key_pyobj {
2277   PyHeapTypeObject ty;
2278   poly1305_key k;
2279 } poly1305key_pyobj;
2280
2281 typedef struct poly1305hash_pyobj {
2282   PyObject_HEAD
2283   unsigned f;
2284 #define f_mask 1u
2285   poly1305_ctx ctx;
2286 } poly1305hash_pyobj;
2287
2288 #define P1305_F(o) (((poly1305hash_pyobj *)(o))->f)
2289 #define P1305_CTX(o) (&((poly1305hash_pyobj *)(o))->ctx)
2290 CONVFUNC(poly1305hash, poly1305_ctx *, P1305_CTX)
2291
2292 static PyObject *poly1305hash_pynew(PyTypeObject *ty,
2293                                     PyObject *arg, PyObject *kw)
2294 {
2295   static const char *const kwlist[] = { "mask", 0 };
2296   poly1305key_pyobj *pk = (poly1305key_pyobj *)ty;
2297   poly1305hash_pyobj *ph;
2298   char *m = 0;
2299   Py_ssize_t sz;
2300
2301   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|s#:new", KWLIST, &m, &sz))
2302     return (0);
2303   if (m && sz != POLY1305_MASKSZ) VALERR("bad mask length");
2304   ph = PyObject_NEW(poly1305hash_pyobj, ty);
2305   ph->f = 0;
2306   if (m) ph->f |= f_mask;
2307   poly1305_macinit(&ph->ctx, &pk->k, m);
2308   Py_INCREF(ty);
2309   return ((PyObject *)ph);
2310 end:
2311   return (0);
2312 }
2313
2314 static PyObject *poly1305key_pynew(PyTypeObject *ty,
2315                                    PyObject *arg, PyObject *kw)
2316 {
2317   static const char *const kwlist[] = { "k", 0 };
2318   poly1305key_pyobj *pk;
2319   char *k;
2320   Py_ssize_t sz;
2321
2322   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#:new", KWLIST, &k, &sz))
2323     goto end;
2324   if (keysz(sz, poly1305_keysz) != sz) VALERR("bad key length");
2325
2326   pk = newtype(ty, 0, 0);
2327   pk->ty.ht_name = PyString_FromString("poly1305(keyed)");
2328   pk->ty.ht_type.tp_basicsize = sizeof(poly1305hash_pyobj);
2329   pk->ty.ht_type.tp_name = PyString_AS_STRING(pk->ty.ht_name);
2330   pk->ty.ht_type.tp_base = poly1305hash_pytype;
2331   Py_INCREF(poly1305key_pytype);
2332   pk->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
2333                              Py_TPFLAGS_BASETYPE |
2334                              Py_TPFLAGS_HEAPTYPE);
2335   pk->ty.ht_type.tp_alloc = PyType_GenericAlloc;
2336   pk->ty.ht_type.tp_free = 0;
2337   pk->ty.ht_type.tp_new = poly1305hash_pynew;
2338   typeready(&pk->ty.ht_type);
2339
2340   poly1305_keyinit(&pk->k, k, sz);
2341   return ((PyObject *)pk);
2342
2343 end:
2344   return (0);
2345 }
2346
2347 static PyObject *poly1305clsget_name(PyObject *me, void *hunoz)
2348   { return (PyString_FromString("poly1305")); }
2349
2350 static PyObject *poly1305clsget_keysz(PyObject *me, void *hunoz)
2351   { return (keysz_pywrap(poly1305_keysz)); }
2352
2353 static PyObject *poly1305clsget_masksz(PyObject *me, void *hunoz)
2354   { return (PyInt_FromLong(POLY1305_MASKSZ)); }
2355
2356 static PyObject *poly1305clsget_tagsz(PyObject *me, void *hunoz)
2357   { return (PyInt_FromLong(POLY1305_TAGSZ)); }
2358
2359 static PyObject *polymeth_copy(PyObject *me, PyObject *arg)
2360 {
2361   poly1305hash_pyobj *ph;
2362   if (!PyArg_ParseTuple(arg, ":copy")) return (0);
2363   ph = PyObject_NEW(poly1305hash_pyobj, me->ob_type);
2364   poly1305_copy(&ph->ctx, P1305_CTX(me));
2365   Py_INCREF(me->ob_type);
2366   return ((PyObject *)ph);
2367 }
2368
2369 static PyObject *polymeth_hash(PyObject *me, PyObject *arg)
2370 {
2371   char *p;
2372   Py_ssize_t sz;
2373   if (!PyArg_ParseTuple(arg, "s#:hash", &p, &sz)) return (0);
2374   poly1305_hash(P1305_CTX(me), p, sz);
2375   RETURN_ME;
2376 }
2377
2378 #define POLYMETH_HASHU_(n, W, w)                                        \
2379   static PyObject *polymeth_hashu##w(PyObject *me, PyObject *arg)       \
2380   {                                                                     \
2381     uint##n x;                                                          \
2382     octet b[SZ_##W];                                                    \
2383     if (!PyArg_ParseTuple(arg, "O&:hashu" #w, convu##n, &x)) return (0); \
2384     STORE##W(b, x); poly1305_hash(P1305_CTX(me), b, sizeof(b));         \
2385     RETURN_ME;                                                          \
2386   }
2387 DOUINTCONV(POLYMETH_HASHU_)
2388
2389 #define POLYMETH_HASHBUF_(n, W, w)                                      \
2390   static PyObject *polymeth_hashbuf##w(PyObject *me, PyObject *arg)     \
2391   {                                                                     \
2392     char *p;                                                            \
2393     Py_ssize_t sz;                                                      \
2394     octet b[SZ_##W];                                                    \
2395     if (!PyArg_ParseTuple(arg, "s#:hashbuf" #w, &p, &sz)) goto end;     \
2396     if (sz > MASK##n) TYERR("string too long");                         \
2397     STORE##W(b, sz); poly1305_hash(P1305_CTX(me), b, sizeof(b));        \
2398     poly1305_hash(P1305_CTX(me), p, sz);                                \
2399     RETURN_ME;                                                          \
2400   end:                                                                  \
2401     return (0);                                                         \
2402   }
2403 DOUINTCONV(POLYMETH_HASHBUF_)
2404
2405 static PyObject *polymeth_hashstrz(PyObject *me, PyObject *arg)
2406 {
2407   char *p;
2408   if (!PyArg_ParseTuple(arg, "s:hashstrz", &p)) return (0);
2409   poly1305_hash(P1305_CTX(me), p, strlen(p) + 1);
2410   RETURN_ME;
2411 }
2412
2413 static PyObject *polymeth_flush(PyObject *me, PyObject *arg)
2414 {
2415   if (!PyArg_ParseTuple(arg, ":flush")) return (0);
2416   poly1305_flush(P1305_CTX(me));
2417   RETURN_ME;
2418 }
2419
2420 static PyObject *polymeth_flushzero(PyObject *me, PyObject *arg)
2421 {
2422   if (!PyArg_ParseTuple(arg, ":flushzero")) return (0);
2423   poly1305_flushzero(P1305_CTX(me));
2424   RETURN_ME;
2425 }
2426
2427 static PyObject *polymeth_concat(PyObject *me, PyObject *arg)
2428 {
2429   PyObject *pre, *suff;
2430   if (!PyArg_ParseTuple(arg, "OO:concat", &pre, &suff)) return (0);
2431   if (!PyObject_TypeCheck(pre, poly1305hash_pytype) ||
2432       !PyObject_TypeCheck(suff, poly1305hash_pytype))
2433     TYERR("wanted a poly1305hash");
2434   if (me->ob_type != pre->ob_type || me->ob_type != suff->ob_type)
2435     TYERR("key mismatch");
2436   if (P1305_CTX(pre)->nbuf) VALERR("prefix is not block-aligned");
2437   poly1305_concat(P1305_CTX(me), P1305_CTX(pre), P1305_CTX(suff));
2438   RETURN_ME;
2439 end:
2440   return (0);
2441 }
2442
2443 static PyObject *polymeth_done(PyObject *me, PyObject *arg)
2444 {
2445   PyObject *rc;
2446   if (!PyArg_ParseTuple(arg, ":done")) return (0);
2447   if (!(P1305_F(me) & f_mask)) VALERR("no mask");
2448   rc = bytestring_pywrap(0, POLY1305_TAGSZ);
2449   poly1305_done(P1305_CTX(me), PyString_AS_STRING(rc));
2450   return (rc);
2451 end:
2452   return (0);
2453 }
2454
2455 static PyGetSetDef poly1305cls_pygetset[] = {
2456 #define GETSETNAME(op, name) poly1305cls##op##_##name
2457   GET   (keysz,                 "PC.keysz -> acceptable key sizes")
2458   GET   (masksz,                "PC.masksz -> mask size")
2459   GET   (tagsz,                 "PC.tagsz -> MAC output size")
2460   GET   (name,                  "PC.name -> name of this kind of MAC")
2461 #undef GETSETNAME
2462   { 0 }
2463 };
2464
2465 static PyMethodDef poly1305hash_pymethods[] = {
2466 #define METHNAME(name) polymeth_##name
2467   METH  (copy,                  "P.copy() -> PP")
2468   METH  (hash,                  "P.hash(M)")
2469 #define METHU_(n, W, w) METH(hashu##w, "P.hashu" #w "(WORD)")
2470   DOUINTCONV(METHU_)
2471 #undef METHU_
2472 #define METHBUF_(n, W, w) METH(hashbuf##w, "P.hashbuf" #w "(BYTES)")
2473   DOUINTCONV(METHBUF_)
2474 #undef METHBUF_
2475   METH  (hashstrz,              "P.hashstrz(STRING)")
2476   METH  (flush,                 "P.flush()")
2477   METH  (flushzero,             "P.flushzero()")
2478   METH  (concat,                "P.concat(PREFIX, SUFFIX)")
2479   METH  (done,                  "P.done() -> TAG")
2480 #undef METHNAME
2481   { 0 }
2482 };
2483
2484 static PyTypeObject poly1305cls_pytype_skel = {
2485   PyObject_HEAD_INIT(0) 0,              /* Header */
2486   "Poly1305Class",                      /* @tp_name@ */
2487   sizeof(PyHeapTypeObject),             /* @tp_basicsize@ */
2488   0,                                    /* @tp_itemsize@ */
2489
2490   0,                                    /* @tp_dealloc@ */
2491   0,                                    /* @tp_print@ */
2492   0,                                    /* @tp_getattr@ */
2493   0,                                    /* @tp_setattr@ */
2494   0,                                    /* @tp_compare@ */
2495   0,                                    /* @tp_repr@ */
2496   0,                                    /* @tp_as_number@ */
2497   0,                                    /* @tp_as_sequence@ */
2498   0,                                    /* @tp_as_mapping@ */
2499   0,                                    /* @tp_hash@ */
2500   0,                                    /* @tp_call@ */
2501   0,                                    /* @tp_str@ */
2502   0,                                    /* @tp_getattro@ */
2503   0,                                    /* @tp_setattro@ */
2504   0,                                    /* @tp_as_buffer@ */
2505   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2506     Py_TPFLAGS_BASETYPE,
2507
2508   /* @tp_doc@ */
2509 "Poly1305 metametaclass.  Best not to ask.",
2510
2511   0,                                    /* @tp_traverse@ */
2512   0,                                    /* @tp_clear@ */
2513   0,                                    /* @tp_richcompare@ */
2514   0,                                    /* @tp_weaklistoffset@ */
2515   0,                                    /* @tp_iter@ */
2516   0,                                    /* @tp_iternext@ */
2517   0,                                    /* @tp_methods@ */
2518   0,                                    /* @tp_members@ */
2519   poly1305cls_pygetset,                 /* @tp_getset@ */
2520   0,                                    /* @tp_base@ */
2521   0,                                    /* @tp_dict@ */
2522   0,                                    /* @tp_descr_get@ */
2523   0,                                    /* @tp_descr_set@ */
2524   0,                                    /* @tp_dictoffset@ */
2525   0,                                    /* @tp_init@ */
2526   PyType_GenericAlloc,                  /* @tp_alloc@ */
2527   abstract_pynew,                       /* @tp_new@ */
2528   0,                                    /* @tp_free@ */
2529   0                                     /* @tp_is_gc@ */
2530 };
2531
2532 static PyTypeObject poly1305key_pytype_skel = {
2533   PyObject_HEAD_INIT(0) 0,              /* Header */
2534   "poly1305",                           /* @tp_name@ */
2535   sizeof(poly1305key_pyobj),            /* @tp_basicsize@ */
2536   0,                                    /* @tp_itemsize@ */
2537
2538   0,                                    /* @tp_dealloc@ */
2539   0,                                    /* @tp_print@ */
2540   0,                                    /* @tp_getattr@ */
2541   0,                                    /* @tp_setattr@ */
2542   0,                                    /* @tp_compare@ */
2543   0,                                    /* @tp_repr@ */
2544   0,                                    /* @tp_as_number@ */
2545   0,                                    /* @tp_as_sequence@ */
2546   0,                                    /* @tp_as_mapping@ */
2547   0,                                    /* @tp_hash@ */
2548   0,                                    /* @tp_call@ */
2549   0,                                    /* @tp_str@ */
2550   0,                                    /* @tp_getattro@ */
2551   0,                                    /* @tp_setattro@ */
2552   0,                                    /* @tp_as_buffer@ */
2553   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2554     Py_TPFLAGS_BASETYPE,
2555
2556   /* @tp_doc@ */
2557 "poly1305(K): Poly1305 key.",
2558
2559   0,                                    /* @tp_traverse@ */
2560   0,                                    /* @tp_clear@ */
2561   0,                                    /* @tp_richcompare@ */
2562   0,                                    /* @tp_weaklistoffset@ */
2563   0,                                    /* @tp_iter@ */
2564   0,                                    /* @tp_iternext@ */
2565   0,                                    /* @tp_methods@ */
2566   0,                                    /* @tp_members@ */
2567   0,                                    /* @tp_getset@ */
2568   0,                                    /* @tp_base@ */
2569   0,                                    /* @tp_dict@ */
2570   0,                                    /* @tp_descr_get@ */
2571   0,                                    /* @tp_descr_set@ */
2572   0,                                    /* @tp_dictoffset@ */
2573   0,                                    /* @tp_init@ */
2574   PyType_GenericAlloc,                  /* @tp_alloc@ */
2575   poly1305key_pynew,                    /* @tp_new@ */
2576   0,                                    /* @tp_free@ */
2577   0                                     /* @tp_is_gc@ */
2578 };
2579
2580 static PyTypeObject poly1305hash_pytype_skel = {
2581   PyObject_HEAD_INIT(0) 0,              /* Header */
2582   "Poly1305Hash",                       /* @tp_name@ */
2583   sizeof(poly1305hash_pyobj),           /* @tp_basicsize@ */
2584   0,                                    /* @tp_itemsize@ */
2585
2586   0,                                    /* @tp_dealloc@ */
2587   0,                                    /* @tp_print@ */
2588   0,                                    /* @tp_getattr@ */
2589   0,                                    /* @tp_setattr@ */
2590   0,                                    /* @tp_compare@ */
2591   0,                                    /* @tp_repr@ */
2592   0,                                    /* @tp_as_number@ */
2593   0,                                    /* @tp_as_sequence@ */
2594   0,                                    /* @tp_as_mapping@ */
2595   0,                                    /* @tp_hash@ */
2596   0,                                    /* @tp_call@ */
2597   0,                                    /* @tp_str@ */
2598   0,                                    /* @tp_getattro@ */
2599   0,                                    /* @tp_setattro@ */
2600   0,                                    /* @tp_as_buffer@ */
2601   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2602     Py_TPFLAGS_BASETYPE,
2603
2604   /* @tp_doc@ */
2605 "Poly1305 MAC context base class.",
2606
2607   0,                                    /* @tp_traverse@ */
2608   0,                                    /* @tp_clear@ */
2609   0,                                    /* @tp_richcompare@ */
2610   0,                                    /* @tp_weaklistoffset@ */
2611   0,                                    /* @tp_iter@ */
2612   0,                                    /* @tp_iternext@ */
2613   poly1305hash_pymethods,               /* @tp_methods@ */
2614   0,                                    /* @tp_members@ */
2615   0,                                    /* @tp_getset@ */
2616   0,                                    /* @tp_base@ */
2617   0,                                    /* @tp_dict@ */
2618   0,                                    /* @tp_descr_get@ */
2619   0,                                    /* @tp_descr_set@ */
2620   0,                                    /* @tp_dictoffset@ */
2621   0,                                    /* @tp_init@ */
2622   PyType_GenericAlloc,                  /* @tp_alloc@ */
2623   abstract_pynew,                       /* @tp_new@ */
2624   0,                                    /* @tp_free@ */
2625   0                                     /* @tp_is_gc@ */
2626 };
2627
2628 /*----- Special snowflake for HSalsa and HChaCha --------------------------*/
2629
2630 #define DEF_HDANCE(DANCE, HDANCE, dance, hdance)                        \
2631   static PyObject *meth_##hdance##_prf(PyObject *me, PyObject *arg)     \
2632   {                                                                     \
2633     dance##_ctx dance;                                                  \
2634     char *k, *n;                                                        \
2635     Py_ssize_t ksz, nsz;                                                \
2636     PyObject *rc;                                                       \
2637     if (!PyArg_ParseTuple(arg, "s#s#:" #hdance "_prf",                  \
2638                           &k, &ksz, &n, &nsz))                          \
2639       goto end;                                                         \
2640     if (ksz != DANCE##_KEYSZ) VALERR("bad key length");                 \
2641     if (nsz != HDANCE##_INSZ) VALERR("bad input length");               \
2642     rc = bytestring_pywrap(0, HSALSA20_OUTSZ);                          \
2643     dance##_init(&dance, k, ksz, 0);                                    \
2644     hdance##_prf(&dance, n, PyString_AS_STRING(rc));                    \
2645     return (rc);                                                        \
2646   end:                                                                  \
2647     return (0);                                                         \
2648   }
2649
2650 DEF_HDANCE(SALSA20, HSALSA20, salsa20, hsalsa20)
2651 DEF_HDANCE(SALSA20, HSALSA20, salsa20, hsalsa2012)
2652 DEF_HDANCE(SALSA20, HSALSA20, salsa20, hsalsa208)
2653
2654 DEF_HDANCE(CHACHA, HCHACHA, chacha, hchacha20)
2655 DEF_HDANCE(CHACHA, HCHACHA, chacha, hchacha12)
2656 DEF_HDANCE(CHACHA, HCHACHA, chacha, hchacha8)
2657
2658 /*----- Keccak-p[1600, n] -------------------------------------------------*/
2659
2660 static PyTypeObject *kxvik_pytype;
2661
2662 typedef struct kxvik_pyobj {
2663   PyObject_HEAD
2664   keccak1600_state s;
2665   unsigned n;
2666 } kxvik_pyobj;
2667
2668 static PyObject *kxvik_pynew(PyTypeObject *ty,
2669                                   PyObject *arg, PyObject *kw)
2670 {
2671   unsigned n = 24;
2672   kxvik_pyobj *rc = 0;
2673   static const char *const kwlist[] = { "nround", 0 };
2674   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:new", KWLIST,
2675                                    convuint, &n))
2676     goto end;
2677   rc = (kxvik_pyobj *)ty->tp_alloc(ty, 0);
2678   rc->n = n;
2679   keccak1600_init(&rc->s);
2680 end:
2681   return ((PyObject *)rc);
2682 }
2683
2684 static PyObject *kxvikmeth_copy(PyObject *me, PyObject *arg)
2685 {
2686   kxvik_pyobj *k = (kxvik_pyobj *)me, *rc = 0;
2687   if (!PyArg_ParseTuple(arg, ":copy")) goto end;
2688   rc = (kxvik_pyobj *)k->ob_type->tp_alloc(k->ob_type, 0);
2689   rc->s = k->s; rc->n = k->n;
2690 end:
2691   return ((PyObject *)rc);
2692 }
2693
2694 static PyObject *kxvikmeth_mix(PyObject *me, PyObject *arg)
2695 {
2696   kxvik_pyobj *k = (kxvik_pyobj *)me;
2697   kludge64 t[25];
2698   const octet *q;
2699   octet buf[8];
2700   unsigned i;
2701   char *p; Py_ssize_t n;
2702
2703   if (!PyArg_ParseTuple(arg, "s#:mix", &p, &n)) goto end;
2704   if (n > 200) VALERR("out of range");
2705   q = (const octet *)p;
2706   i = 0;
2707   while (n > 8) { LOAD64_L_(t[i], q); i++; q += 8; n -= 8; }
2708   if (n) {
2709     memcpy(buf, q, n); memset(buf + n, 0, 8 - n);
2710     LOAD64_L_(t[i], buf); i++;
2711   }
2712   keccak1600_mix(&k->s, t, i);
2713   RETURN_ME;
2714 end:
2715   return (0);
2716 }
2717
2718 static PyObject *kxvikmeth_extract(PyObject *me, PyObject *arg)
2719 {
2720   kxvik_pyobj *k = (kxvik_pyobj *)me;
2721   PyObject *rc = 0;
2722   kludge64 t[25];
2723   octet *q, buf[8];
2724   unsigned i;
2725   unsigned n;
2726
2727   if (!PyArg_ParseTuple(arg, "O&:mix", convuint, &n)) goto end;
2728   if (n > 200) VALERR("out of range");
2729   rc = bytestring_pywrap(0, n);
2730   q = (octet *)PyString_AS_STRING(rc);
2731   keccak1600_extract(&k->s, t, (n + 7)/8);
2732   i = 0;
2733   while (n > 8) { STORE64_L_(q, t[i]); i++; q += 8; n -= 8; }
2734   if (n) { STORE64_L_(buf, t[i]); memcpy(q, buf, n); }
2735 end:
2736   return (rc);
2737 }
2738
2739 static PyObject *kxvikmeth_step(PyObject *me, PyObject *arg)
2740 {
2741   kxvik_pyobj *k = (kxvik_pyobj *)me;
2742   if (!PyArg_ParseTuple(arg, ":step")) return (0);
2743   keccak1600_p(&k->s, &k->s, k->n);
2744   RETURN_ME;
2745 }
2746
2747 static PyObject *kxvikget_nround(PyObject *me, void *hunoz)
2748 {
2749   kxvik_pyobj *k = (kxvik_pyobj *)me;
2750   return (PyInt_FromLong(k->n));
2751 }
2752
2753 static int kxvikset_nround(PyObject *me, PyObject *val, void *hunoz)
2754 {
2755   kxvik_pyobj *k = (kxvik_pyobj *)me;
2756   unsigned n;
2757
2758   if (!convuint(val, &n)) return (-1);
2759   k->n = n;
2760   return (0);
2761 }
2762
2763 static PyGetSetDef kxvik_pygetset[] = {
2764 #define GETSETNAME(op, name) kxvik##op##_##name
2765   GETSET(nround,                "KECCAK.nround -> number of rounds")
2766 #undef GETSETNAME
2767   { 0 }
2768 };
2769
2770 static PyMethodDef kxvik_pymethods[] = {
2771 #define METHNAME(func) kxvikmeth_##func
2772   METH  (copy,                  "KECCAK.copy() -> KECCAK'")
2773   METH  (mix,                   "KECCAK.mix(DATA)")
2774   METH  (extract,               "KECCAK.extract(NOCTETS)")
2775   METH  (step,                  "KECCAK.step()")
2776 #undef METHNAME
2777   { 0 }
2778 };
2779
2780 static PyTypeObject kxvik_pytype_skel = {
2781   PyObject_HEAD_INIT(0) 0,              /* Header */
2782   "Keccak1600",                         /* @tp_name@ */
2783   sizeof(kxvik_pyobj),                  /* @tp_basicsize@ */
2784   0,                                    /* @tp_itemsize@ */
2785
2786   0,                                    /* @tp_dealloc@ */
2787   0,                                    /* @tp_print@ */
2788   0,                                    /* @tp_getattr@ */
2789   0,                                    /* @tp_setattr@ */
2790   0,                                    /* @tp_compare@ */
2791   0,                                    /* @tp_repr@ */
2792   0,                                    /* @tp_as_number@ */
2793   0,                                    /* @tp_as_sequence@ */
2794   0,                                    /* @tp_as_mapping@ */
2795   0,                                    /* @tp_hash@ */
2796   0,                                    /* @tp_call@ */
2797   0,                                    /* @tp_str@ */
2798   0,                                    /* @tp_getattro@ */
2799   0,                                    /* @tp_setattro@ */
2800   0,                                    /* @tp_as_buffer@ */
2801   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
2802     Py_TPFLAGS_BASETYPE,
2803
2804   /* @tp_doc@ */
2805 "Keccak1600([nround = 24]): Keccak-p[1600, n] state.",
2806
2807   0,                                    /* @tp_traverse@ */
2808   0,                                    /* @tp_clear@ */
2809   0,                                    /* @tp_richcompare@ */
2810   0,                                    /* @tp_weaklistoffset@ */
2811   0,                                    /* @tp_iter@ */
2812   0,                                    /* @tp_iternext@ */
2813   kxvik_pymethods,                      /* @tp_methods@ */
2814   0,                                    /* @tp_members@ */
2815   kxvik_pygetset,                       /* @tp_getset@ */
2816   0,                                    /* @tp_base@ */
2817   0,                                    /* @tp_dict@ */
2818   0,                                    /* @tp_descr_get@ */
2819   0,                                    /* @tp_descr_set@ */
2820   0,                                    /* @tp_dictoffset@ */
2821   0,                                    /* @tp_init@ */
2822   PyType_GenericAlloc,                  /* @tp_alloc@ */
2823   kxvik_pynew,                          /* @tp_new@ */
2824   0,                                    /* @tp_free@ */
2825   0                                     /* @tp_is_gc@ */
2826 };
2827
2828 static PyTypeObject *shake_pytype, *shake128_pytype, *shake256_pytype;
2829
2830 typedef struct shake_pyobj {
2831   PyObject_HEAD
2832   int st;
2833   shake_ctx h;
2834 } shake_pyobj;
2835
2836 #define SHAKE_H(o) (&((shake_pyobj *)(o))->h)
2837 #define SHAKE_ST(o) (((shake_pyobj *)(o))->st)
2838
2839 static PyObject *shake_dopynew(void (*initfn)(shake_ctx *,
2840                                               const void *, size_t,
2841                                               const void *, size_t),
2842                                PyTypeObject *ty,
2843                                PyObject *arg, PyObject *kw)
2844 {
2845   shake_pyobj *rc = 0;
2846   char *p = 0, *f = 0;
2847   Py_ssize_t psz = 0, fsz = 0;
2848   static const char *const kwlist[] = { "perso", "func", 0 };
2849
2850   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|s#s#:new", KWLIST,
2851                                    &p, &psz, &f, &fsz))
2852     goto end;
2853   rc = (shake_pyobj *)ty->tp_alloc(ty, 0);
2854   initfn(&rc->h, f, fsz, p, psz);
2855   rc->st = 0;
2856 end:
2857   return ((PyObject *)rc);
2858 }
2859
2860 static PyObject *shake128_pynew(PyTypeObject *ty,
2861                                 PyObject *arg, PyObject *kw)
2862   { return (shake_dopynew(cshake128_init, ty, arg, kw)); }
2863
2864 static PyObject *shake256_pynew(PyTypeObject *ty,
2865                                 PyObject *arg, PyObject *kw)
2866   { return (shake_dopynew(cshake256_init, ty, arg, kw)); }
2867
2868 static int shake_check(PyObject *me, int st)
2869 {
2870   if (SHAKE_ST(me) != st) VALERR("wrong state");
2871   return (0);
2872 end:
2873   return (-1);
2874 }
2875
2876 static PyObject *shakemeth_hash(PyObject *me, PyObject *arg)
2877 {
2878   char *p;
2879   Py_ssize_t sz;
2880   if (!PyArg_ParseTuple(arg, "s#:hash", &p, &sz)) return (0);
2881   if (shake_check(me, 0)) return (0);
2882   shake_hash(SHAKE_H(me), p, sz);
2883   RETURN_ME;
2884 }
2885
2886 #define SHAKEMETH_HASHU_(n, W, w)                                       \
2887   static PyObject *shakemeth_hashu##w(PyObject *me, PyObject *arg)      \
2888   {                                                                     \
2889     uint##n x;                                                          \
2890     octet b[SZ_##W];                                                    \
2891     if (!PyArg_ParseTuple(arg, "O&:hashu" #w, convu##n, &x)) return (0); \
2892     if (shake_check(me, 0)) return (0);                                 \
2893     STORE##W(b, x); shake_hash(SHAKE_H(me), b, sizeof(b));              \
2894     RETURN_ME;                                                          \
2895   }
2896 DOUINTCONV(SHAKEMETH_HASHU_)
2897
2898 #define SHAKEMETH_HASHBUF_(n, W, w)                                     \
2899   static PyObject *shakemeth_hashbuf##w(PyObject *me, PyObject *arg)    \
2900   {                                                                     \
2901     char *p;                                                            \
2902     Py_ssize_t sz;                                                      \
2903     octet b[SZ_##W];                                                    \
2904     if (!PyArg_ParseTuple(arg, "s#:hashbuf" #w, &p, &sz)) goto end;     \
2905     if (sz > MASK##n) TYERR("string too long");                         \
2906     if (shake_check(me, 0)) goto end;                                   \
2907     STORE##W(b, sz); shake_hash(SHAKE_H(me), b, sizeof(b));             \
2908     shake_hash(SHAKE_H(me), p, sz);                                     \
2909     RETURN_ME;                                                          \
2910   end:                                                                  \
2911     return (0);                                                         \
2912   }
2913 DOUINTCONV(SHAKEMETH_HASHBUF_)
2914
2915 static PyObject *shakemeth_hashstrz(PyObject *me, PyObject *arg)
2916 {
2917   char *p;
2918   if (!PyArg_ParseTuple(arg, "s:hashstrz", &p)) return (0);
2919   if (shake_check(me, 0)) return (0);
2920   shake_hash(SHAKE_H(me), p, strlen(p) + 1);
2921   RETURN_ME;
2922 }
2923
2924 static PyObject *shakemeth_xof(PyObject *me, PyObject *arg)
2925 {
2926   if (!PyArg_ParseTuple(arg, ":xof")) goto end;
2927   if (shake_check(me, 0)) goto end;
2928   shake_xof(SHAKE_H(me));
2929   SHAKE_ST(me) = 1;
2930   RETURN_ME;
2931 end:
2932   return (0);
2933 }
2934
2935 static PyObject *shakemeth_done(PyObject *me, PyObject *arg)
2936 {
2937   PyObject *rc = 0;
2938   size_t n;
2939   if (!PyArg_ParseTuple(arg, "O&:done", convszt, &n)) goto end;
2940   if (shake_check(me, 0)) goto end;
2941   rc = bytestring_pywrap(0, n);
2942   shake_done(SHAKE_H(me), PyString_AS_STRING(rc), n);
2943   SHAKE_ST(me) = -1;
2944 end:
2945   return (rc);
2946 }
2947
2948 static PyObject *shakemeth_copy(PyObject *me, PyObject *arg)
2949 {
2950   shake_pyobj *rc = 0;
2951
2952   if (!PyArg_ParseTuple(arg, ":copy")) goto end;
2953   rc = PyObject_NEW(shake_pyobj, me->ob_type);
2954   rc->h = *SHAKE_H(me);
2955   rc->st = SHAKE_ST(me);
2956 end:
2957   return ((PyObject *)me);
2958 }
2959
2960 static PyObject *shakemeth_get(PyObject *me, PyObject *arg)
2961 {
2962   PyObject *rc = 0;
2963   size_t sz;
2964
2965   if (!PyArg_ParseTuple(arg, "O&:get", convszt, &sz)) goto end;
2966   if (shake_check(me, 1)) goto end;
2967   rc = bytestring_pywrap(0, sz);
2968   shake_get(SHAKE_H(me), PyString_AS_STRING(rc), sz);
2969 end:
2970   return (rc);
2971 }
2972
2973 static PyObject *shakemeth_mask(PyObject *me, PyObject *arg)
2974 {
2975   PyObject *rc = 0;
2976   char *p; Py_ssize_t sz;
2977
2978   if (!PyArg_ParseTuple(arg, "s#:mask", &p, &sz)) goto end;
2979   if (shake_check(me, 1)) goto end;
2980   rc = bytestring_pywrap(0, sz);
2981   shake_mask(SHAKE_H(me), p, PyString_AS_STRING(rc), sz);
2982 end:
2983   return (rc);
2984 }
2985
2986 static PyObject *shakeget_rate(PyObject *me, void *hunoz)
2987   { return (PyInt_FromLong(SHAKE_H(me)->h.r)); }
2988
2989 static PyObject *shakeget_buffered(PyObject *me, void *hunoz)
2990   { return (PyInt_FromLong(SHAKE_H(me)->h.n)); }
2991
2992 static PyObject *shakeget_state(PyObject *me, void *hunoz)
2993 {
2994   int st = SHAKE_ST(me);
2995   return (PyString_FromString(st == 0 ? "absorb" :
2996                               st == 1 ? "squeeze" : "dead"));
2997 }
2998
2999 static PyGetSetDef shake_pygetset[] = {
3000 #define GETSETNAME(op, name) shake##op##_##name
3001   GET   (rate,                  "S.rate -> rate, in bytes")
3002   GET   (buffered,              "S.buffered -> amount currently buffered")
3003   GET   (state,                 "S.state -> `absorb', `squeeze', `dead'")
3004 #undef GETSETNAME
3005   { 0 }
3006 };
3007
3008 static PyMethodDef shake_pymethods[] = {
3009 #define METHNAME(func) shakemeth_##func
3010   METH  (copy,                  "S.copy() -> SS")
3011   METH  (hash,                  "S.hash(M)")
3012 #define METHU_(n, W, w) METH(hashu##w, "S.hashu" #w "(WORD)")
3013   DOUINTCONV(METHU_)
3014 #undef METHU_
3015 #define METHBUF_(n, W, w) METH(hashbuf##w, "S.hashbuf" #w "(BYTES)")
3016   DOUINTCONV(METHBUF_)
3017 #undef METHBUF_
3018   METH  (hashstrz,              "S.hashstrz(STRING)")
3019   METH  (xof,                   "S.xof()")
3020   METH  (done,                  "S.done(LEN) ->H")
3021   METH  (get,                   "S.get(LEN) -> H")
3022   METH  (mask,                  "S.mask(M) -> C")
3023 #undef METHNAME
3024   { 0 }
3025 };
3026
3027 static PyTypeObject shake_pytype_skel = {
3028   PyObject_HEAD_INIT(0) 0,              /* Header */
3029   "Shake",                              /* @tp_name@ */
3030   sizeof(shake_pyobj),                  /* @tp_basicsize@ */
3031   0,                                    /* @tp_itemsize@ */
3032
3033   0,                                    /* @tp_dealloc@ */
3034   0,                                    /* @tp_print@ */
3035   0,                                    /* @tp_getattr@ */
3036   0,                                    /* @tp_setattr@ */
3037   0,                                    /* @tp_compare@ */
3038   0,                                    /* @tp_repr@ */
3039   0,                                    /* @tp_as_number@ */
3040   0,                                    /* @tp_as_sequence@ */
3041   0,                                    /* @tp_as_mapping@ */
3042   0,                                    /* @tp_hash@ */
3043   0,                                    /* @tp_call@ */
3044   0,                                    /* @tp_str@ */
3045   0,                                    /* @tp_getattro@ */
3046   0,                                    /* @tp_setattro@ */
3047   0,                                    /* @tp_as_buffer@ */
3048   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
3049     Py_TPFLAGS_BASETYPE,
3050
3051   /* @tp_doc@ */
3052 "SHAKE/cSHAKE base class.",
3053
3054   0,                                    /* @tp_traverse@ */
3055   0,                                    /* @tp_clear@ */
3056   0,                                    /* @tp_richcompare@ */
3057   0,                                    /* @tp_weaklistoffset@ */
3058   0,                                    /* @tp_iter@ */
3059   0,                                    /* @tp_iternext@ */
3060   shake_pymethods,                      /* @tp_methods@ */
3061   0,                                    /* @tp_members@ */
3062   shake_pygetset,                       /* @tp_getset@ */
3063   0,                                    /* @tp_base@ */
3064   0,                                    /* @tp_dict@ */
3065   0,                                    /* @tp_descr_get@ */
3066   0,                                    /* @tp_descr_set@ */
3067   0,                                    /* @tp_dictoffset@ */
3068   0,                                    /* @tp_init@ */
3069   PyType_GenericAlloc,                  /* @tp_alloc@ */
3070   abstract_pynew,                       /* @tp_new@ */
3071   0,                                    /* @tp_free@ */
3072   0                                     /* @tp_is_gc@ */
3073 };
3074
3075 static PyTypeObject shake128_pytype_skel = {
3076   PyObject_HEAD_INIT(0) 0,              /* Header */
3077   "Shake128",                           /* @tp_name@ */
3078   0,                                    /* @tp_basicsize@ */
3079   0,                                    /* @tp_itemsize@ */
3080
3081   0,                                    /* @tp_dealloc@ */
3082   0,                                    /* @tp_print@ */
3083   0,                                    /* @tp_getattr@ */
3084   0,                                    /* @tp_setattr@ */
3085   0,                                    /* @tp_compare@ */
3086   0,                                    /* @tp_repr@ */
3087   0,                                    /* @tp_as_number@ */
3088   0,                                    /* @tp_as_sequence@ */
3089   0,                                    /* @tp_as_mapping@ */
3090   0,                                    /* @tp_hash@ */
3091   0,                                    /* @tp_call@ */
3092   0,                                    /* @tp_str@ */
3093   0,                                    /* @tp_getattro@ */
3094   0,                                    /* @tp_setattro@ */
3095   0,                                    /* @tp_as_buffer@ */
3096   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
3097     Py_TPFLAGS_BASETYPE,
3098
3099   /* @tp_doc@ */
3100 "Shake128([perso = STR], [func = STR]): SHAKE128/cSHAKE128 XOF.",
3101
3102   0,                                    /* @tp_traverse@ */
3103   0,                                    /* @tp_clear@ */
3104   0,                                    /* @tp_richcompare@ */
3105   0,                                    /* @tp_weaklistoffset@ */
3106   0,                                    /* @tp_iter@ */
3107   0,                                    /* @tp_iternext@ */
3108   0,                                    /* @tp_methods@ */
3109   0,                                    /* @tp_members@ */
3110   0,                                    /* @tp_getset@ */
3111   0,                                    /* @tp_base@ */
3112   0,                                    /* @tp_dict@ */
3113   0,                                    /* @tp_descr_get@ */
3114   0,                                    /* @tp_descr_set@ */
3115   0,                                    /* @tp_dictoffset@ */
3116   0,                                    /* @tp_init@ */
3117   PyType_GenericAlloc,                  /* @tp_alloc@ */
3118   shake128_pynew,                       /* @tp_new@ */
3119   0,                                    /* @tp_free@ */
3120   0                                     /* @tp_is_gc@ */
3121 };
3122
3123 static PyTypeObject shake256_pytype_skel = {
3124   PyObject_HEAD_INIT(0) 0,              /* Header */
3125   "Shake256",                           /* @tp_name@ */
3126   0,                                    /* @tp_basicsize@ */
3127   0,                                    /* @tp_itemsize@ */
3128
3129   0,                                    /* @tp_dealloc@ */
3130   0,                                    /* @tp_print@ */
3131   0,                                    /* @tp_getattr@ */
3132   0,                                    /* @tp_setattr@ */
3133   0,                                    /* @tp_compare@ */
3134   0,                                    /* @tp_repr@ */
3135   0,                                    /* @tp_as_number@ */
3136   0,                                    /* @tp_as_sequence@ */
3137   0,                                    /* @tp_as_mapping@ */
3138   0,                                    /* @tp_hash@ */
3139   0,                                    /* @tp_call@ */
3140   0,                                    /* @tp_str@ */
3141   0,                                    /* @tp_getattro@ */
3142   0,                                    /* @tp_setattro@ */
3143   0,                                    /* @tp_as_buffer@ */
3144   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
3145     Py_TPFLAGS_BASETYPE,
3146
3147   /* @tp_doc@ */
3148 "Shake256([perso = STR], [func = STR]): SHAKE256/cSHAKE256 XOF.",
3149
3150   0,                                    /* @tp_traverse@ */
3151   0,                                    /* @tp_clear@ */
3152   0,                                    /* @tp_richcompare@ */
3153   0,                                    /* @tp_weaklistoffset@ */
3154   0,                                    /* @tp_iter@ */
3155   0,                                    /* @tp_iternext@ */
3156   0,                                    /* @tp_methods@ */
3157   0,                                    /* @tp_members@ */
3158   0,                                    /* @tp_getset@ */
3159   0,                                    /* @tp_base@ */
3160   0,                                    /* @tp_dict@ */
3161   0,                                    /* @tp_descr_get@ */
3162   0,                                    /* @tp_descr_set@ */
3163   0,                                    /* @tp_dictoffset@ */
3164   0,                                    /* @tp_init@ */
3165   PyType_GenericAlloc,                  /* @tp_alloc@ */
3166   shake256_pynew,                       /* @tp_new@ */
3167   0,                                    /* @tp_free@ */
3168   0                                     /* @tp_is_gc@ */
3169 };
3170
3171 /*----- Pseudorandom permutations -----------------------------------------*/
3172
3173 static PyTypeObject *gcprp_pytype, *gprp_pytype;
3174
3175 typedef struct prpinfo {
3176   const char *name;
3177   const octet *keysz;
3178   size_t ctxsz;
3179   size_t blksz;
3180   void (*init)(void *, const void *, size_t);
3181   void (*eblk)(void *, const void *, void *);
3182   void (*dblk)(void *, const void *, void *);
3183 } prpinfo;
3184
3185 #define PRP_DEF(PRE, pre)                                               \
3186   static void pre##_prpinit(void *ctx, const void *k, size_t ksz)       \
3187     { pre##_init(ctx, k, ksz); }                                        \
3188   static void pre##_prpeblk(void *ctx, const void *in, void *out)       \
3189   {                                                                     \
3190     uint32 w[PRE##_BLKSZ/4]; BLKC_LOAD(PRE, w, in);                     \
3191     pre##_eblk(ctx, w, w); BLKC_STORE(PRE, out, w);                     \
3192   }                                                                     \
3193   static void pre##_prpdblk(void *ctx, const void *in, void *out)       \
3194   {                                                                     \
3195     uint32 w[PRE##_BLKSZ/4]; BLKC_LOAD(PRE, w, in);                     \
3196     pre##_dblk(ctx, w, w); BLKC_STORE(PRE, out, w);                     \
3197   }                                                                     \
3198   static const prpinfo pre##_prpinfo = {                                \
3199     #pre, pre##_keysz, sizeof(pre##_ctx), PRE##_BLKSZ,                  \
3200     pre##_prpinit, pre##_prpeblk, pre##_prpdblk                         \
3201   };
3202 PRPS(PRP_DEF)
3203
3204 static const struct prpinfo *const gprptab[] = {
3205 #define PRP_ENTRY(PRE, pre) &pre##_prpinfo,
3206   PRPS(PRP_ENTRY)
3207   0
3208 };
3209
3210 typedef struct gcprp_pyobj {
3211   PyHeapTypeObject ty;
3212   const prpinfo *prp;
3213 } gcprp_pyobj;
3214 #define GCPRP_PRP(o) (((gcprp_pyobj *)(o))->prp)
3215
3216 typedef struct gprp_pyobj {
3217   PyObject_HEAD
3218   const prpinfo *prp;
3219 } gprp_pyobj;
3220 #define GPRP_PRP(o) (((gprp_pyobj *)(o))->prp)
3221 #define GPRP_CTX(o) (((gprp_pyobj *)(o)) + 1)
3222
3223 typedef struct prp {
3224   const prpinfo *prp;
3225   void *ctx;
3226 } prp;
3227
3228 static PyObject *gprp_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
3229 {
3230   static const char *const kwlist[] = { "key", 0 };
3231   char *k;
3232   Py_ssize_t sz;
3233   const prpinfo *prp = GCPRP_PRP(ty);
3234   PyObject *me;
3235
3236   if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#:new", KWLIST, &k, &sz))
3237     goto end;
3238   if (keysz(sz, prp->keysz) != sz) VALERR("bad key length");
3239   me = (PyObject *)ty->tp_alloc(ty, 0);
3240   GPRP_PRP(me) = prp;
3241   prp->init(GPRP_CTX(me), k, sz);
3242   Py_INCREF(me);
3243   return (me);
3244 end:
3245   return (0);
3246 }
3247
3248 static void gprp_pydealloc(PyObject *me)
3249   { Py_DECREF(me->ob_type); FREEOBJ(me); }
3250
3251 static PyObject *gcprp_pywrap(const prpinfo *prp)
3252 {
3253   gcprp_pyobj *g = newtype(gcprp_pytype, 0, prp->name);
3254   g->prp = prp;
3255   g->ty.ht_type.tp_basicsize = sizeof(gprp_pyobj) + prp->ctxsz;
3256   g->ty.ht_type.tp_base = gprp_pytype;
3257   Py_INCREF(gprp_pytype);
3258   g->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
3259                             Py_TPFLAGS_BASETYPE |
3260                             Py_TPFLAGS_HEAPTYPE);
3261   g->ty.ht_type.tp_alloc = PyType_GenericAlloc;
3262   g->ty.ht_type.tp_free = 0;
3263   g->ty.ht_type.tp_new = gprp_pynew;
3264   typeready(&g->ty.ht_type);
3265   return ((PyObject *)g);
3266 }
3267
3268 static PyObject *gcpget_name(PyObject *me, void *hunoz)
3269   { return (PyString_FromString(GCPRP_PRP(me)->name)); }
3270 static PyObject *gcpget_keysz(PyObject *me, void *hunoz)
3271   { return (keysz_pywrap(GCPRP_PRP(me)->keysz)); }
3272 static PyObject *gcpget_blksz(PyObject *me, void *hunoz)
3273   { return (PyInt_FromLong(GCPRP_PRP(me)->blksz)); }
3274
3275 static PyObject *gpmeth_encrypt(PyObject *me, PyObject *arg)
3276 {
3277   char *p;
3278   Py_ssize_t n;
3279   PyObject *rc = 0;
3280
3281   if (!PyArg_ParseTuple(arg, "s#:encrypt", &p, &n)) goto end;
3282   if (n != GPRP_PRP(me)->blksz) VALERR("incorrect block length");
3283   rc = bytestring_pywrap(0, n);
3284   GPRP_PRP(me)->eblk(GPRP_CTX(me), p, PyString_AS_STRING(rc));
3285 end:
3286   return (rc);
3287 }
3288
3289 static PyObject *gpmeth_decrypt(PyObject *me, PyObject *arg)
3290 {
3291   char *p;
3292   Py_ssize_t n;
3293   PyObject *rc = 0;
3294
3295   if (!PyArg_ParseTuple(arg, "s#:decrypt", &p, &n)) goto end;
3296   if (n != GPRP_PRP(me)->blksz) VALERR("incorrect block length");
3297   rc = bytestring_pywrap(0, n);
3298   GPRP_PRP(me)->dblk(GPRP_CTX(me), p, PyString_AS_STRING(rc));
3299 end:
3300   return (rc);
3301 }
3302
3303 static PyGetSetDef gcprp_pygetset[] = {
3304 #define GETSETNAME(op, name) gcp##op##_##name
3305   GET   (keysz,                 "CP.keysz -> acceptable key sizes")
3306   GET   (blksz,                 "CP.blksz -> block size")
3307   GET   (name,                  "CP.name -> name of this kind of PRP")
3308 #undef GETSETNAME
3309   { 0 }
3310 };
3311
3312 static PyMethodDef gprp_pymethods[] = {
3313 #define METHNAME(name) gpmeth_##name
3314   METH  (encrypt,               "P.encrypt(PT) -> CT")
3315   METH  (decrypt,               "P.decrypt(CT) -> PT")
3316 #undef METHNAME
3317   { 0 }
3318 };
3319
3320 static PyTypeObject gcprp_pytype_skel = {
3321   PyObject_HEAD_INIT(0) 0,              /* Header */
3322   "GCPRP",                              /* @tp_name@ */
3323   sizeof(gcprp_pyobj),                  /* @tp_basicsize@ */
3324   0,                                    /* @tp_itemsize@ */
3325
3326   0,                                    /* @tp_dealloc@ */
3327   0,                                    /* @tp_print@ */
3328   0,                                    /* @tp_getattr@ */
3329   0,                                    /* @tp_setattr@ */
3330   0,                                    /* @tp_compare@ */
3331   0,                                    /* @tp_repr@ */
3332   0,                                    /* @tp_as_number@ */
3333   0,                                    /* @tp_as_sequence@ */
3334   0,                                    /* @tp_as_mapping@ */
3335   0,                                    /* @tp_hash@ */
3336   0,                                    /* @tp_call@ */
3337   0,                                    /* @tp_str@ */
3338   0,                                    /* @tp_getattro@ */
3339   0,                                    /* @tp_setattro@ */
3340   0,                                    /* @tp_as_buffer@ */
3341   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
3342     Py_TPFLAGS_BASETYPE,
3343
3344   /* @tp_doc@ */
3345 "Pseudorandom permutation metaclass.",
3346
3347   0,                                    /* @tp_traverse@ */
3348   0,                                    /* @tp_clear@ */
3349   0,                                    /* @tp_richcompare@ */
3350   0,                                    /* @tp_weaklistoffset@ */
3351   0,                                    /* @tp_iter@ */
3352   0,                                    /* @tp_iternext@ */
3353   0,                                    /* @tp_methods@ */
3354   0,                                    /* @tp_members@ */
3355   gcprp_pygetset,                       /* @tp_getset@ */
3356   0,                                    /* @tp_base@ */
3357   0,                                    /* @tp_dict@ */
3358   0,                                    /* @tp_descr_get@ */
3359   0,                                    /* @tp_descr_set@ */
3360   0,                                    /* @tp_dictoffset@ */
3361   0,                                    /* @tp_init@ */
3362   PyType_GenericAlloc,                  /* @tp_alloc@ */
3363   abstract_pynew,                       /* @tp_new@ */
3364   0,                                    /* @tp_free@ */
3365   0                                     /* @tp_is_gc@ */
3366 };
3367
3368 static PyTypeObject gprp_pytype_skel = {
3369   PyObject_HEAD_INIT(0) 0,              /* Header */
3370   "GPRP",                               /* @tp_name@ */
3371   sizeof(gprp_pyobj),                   /* @tp_basicsize@ */
3372   0,                                    /* @tp_itemsize@ */
3373
3374   gprp_pydealloc,                       /* @tp_dealloc@ */
3375   0,                                    /* @tp_print@ */
3376   0,                                    /* @tp_getattr@ */
3377   0,                                    /* @tp_setattr@ */
3378   0,                                    /* @tp_compare@ */
3379   0,                                    /* @tp_repr@ */
3380   0,                                    /* @tp_as_number@ */
3381   0,                                    /* @tp_as_sequence@ */
3382   0,                                    /* @tp_as_mapping@ */
3383   0,                                    /* @tp_hash@ */
3384   0,                                    /* @tp_call@ */
3385   0,                                    /* @tp_str@ */
3386   0,                                    /* @tp_getattro@ */
3387   0,                                    /* @tp_setattro@ */
3388   0,                                    /* @tp_as_buffer@ */
3389   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
3390     Py_TPFLAGS_BASETYPE,
3391
3392   /* @tp_doc@ */
3393 "Pseudorandom permutation, abstract base class.",
3394
3395   0,                                    /* @tp_traverse@ */
3396   0,                                    /* @tp_clear@ */
3397   0,                                    /* @tp_richcompare@ */
3398   0,                                    /* @tp_weaklistoffset@ */
3399   0,                                    /* @tp_iter@ */
3400   0,                                    /* @tp_iternext@ */
3401   gprp_pymethods,                       /* @tp_methods@ */
3402   0,                                    /* @tp_members@ */
3403   0,                                    /* @tp_getset@ */
3404   0,                                    /* @tp_base@ */
3405   0,                                    /* @tp_dict@ */
3406   0,                                    /* @tp_descr_get@ */
3407   0,                                    /* @tp_descr_set@ */
3408   0,                                    /* @tp_dictoffset@ */
3409   0,                                    /* @tp_init@ */
3410   PyType_GenericAlloc,                  /* @tp_alloc@ */
3411   abstract_pynew,                       /* @tp_new@ */
3412   0,                                    /* @tp_free@ */
3413   0                                     /* @tp_is_gc@ */
3414 };
3415
3416 /*----- Main code ---------------------------------------------------------*/
3417
3418 static PyMethodDef methods[] = {
3419 #define METHNAME(func) meth_##func
3420   METH  (_KeySZ_fromdl,         "\
3421 fromdl(N) -> M: convert integer discrete log field size to work factor")
3422   METH  (_KeySZ_fromschnorr,    "\
3423 fromschnorr(N) -> M: convert Schnorr group order to work factor")
3424   METH  (_KeySZ_fromif,         "\
3425 fromif(N) -> M: convert integer factorization problem size to work factor")
3426   METH  (_KeySZ_fromec,         "\
3427 fromec(N) -> M: convert elliptic curve group order to work factor")
3428   METH  (_KeySZ_todl,           "\
3429 todl(N) -> M: convert work factor to integer discrete log field size")
3430   METH  (_KeySZ_toschnorr,      "\
3431 toschnorr(N) -> M: convert work factor to Schnorr group order")
3432   METH  (_KeySZ_toif,           "\
3433 toif(N) -> M: convert work factor to integer factorization problem size")
3434   METH  (_KeySZ_toec,           "\
3435 toec(N) -> M: convert work factor to elliptic curve group order")
3436   METH  (_KeySZ_toec,           "\
3437 toec(N) -> M: convert work factor to elliptic curve group order")
3438 #define METH_HDANCE(hdance, HDance) METH(hdance##_prf, "\
3439 " #hdance "_prf(K, N) -> H: calculate " HDance " hash of N with K")
3440   METH_HDANCE(hsalsa20, "HSalsa20")
3441   METH_HDANCE(hsalsa2012, "HSalsa20/12")
3442   METH_HDANCE(hsalsa208, "HSalsa20/8")
3443   METH_HDANCE(hchacha20, "HChaCha20")
3444   METH_HDANCE(hchacha12, "HChaCha12")
3445   METH_HDANCE(hchacha8, "HChaCha8")
3446 #undef METH_DANCE
3447 #undef METHNAME
3448   { 0 }
3449 };
3450
3451 void algorithms_pyinit(void)
3452 {
3453   INITTYPE(keysz, root);
3454   INITTYPE(keyszany, keysz);
3455   INITTYPE(keyszrange, keysz);
3456   INITTYPE(keyszset, keysz);
3457   INITTYPE(gccipher, type);
3458   INITTYPE(gcipher, root);
3459   INITTYPE(gcaead, type);
3460   INITTYPE(gaeadkey, root);
3461   INITTYPE(gcaeadaad, type);
3462   INITTYPE(gaeadaad, root);
3463   INITTYPE(gcaeadenc, type);
3464   INITTYPE(gaeadenc, root);
3465   INITTYPE(gcaeaddec, type);
3466   INITTYPE(gaeaddec, root);
3467   INITTYPE(gchash, type);
3468   INITTYPE(ghash, root);
3469   INITTYPE(gcmac, type);
3470   INITTYPE(gmac, type);
3471   INITTYPE(gmhash, ghash);
3472   INITTYPE(poly1305cls, type);
3473   INITTYPE_META(poly1305key, type, poly1305cls);
3474   INITTYPE(poly1305hash, root);
3475   INITTYPE(kxvik, root);
3476   INITTYPE(shake, root);
3477   INITTYPE(shake128, shake);
3478   INITTYPE(shake256, shake);
3479   INITTYPE(gcprp, type);
3480   INITTYPE(gprp, root);
3481   addmethods(methods);
3482 }
3483
3484 GEN(gcciphers, cipher)
3485 GEN(gcaeads, aead)
3486 GEN(gchashes, hash)
3487 GEN(gcmacs, mac)
3488 #define gcprp prpinfo
3489 GEN(gcprps, prp)
3490
3491 void algorithms_pyinsert(PyObject *mod)
3492 {
3493   PyObject *d;
3494   INSERT("KeySZ", keysz_pytype);
3495   INSERT("KeySZAny", keyszany_pytype);
3496   INSERT("KeySZRange", keyszrange_pytype);
3497   INSERT("KeySZSet", keyszset_pytype);
3498   INSERT("GCCipher", gccipher_pytype);
3499   INSERT("GCipher", gcipher_pytype);
3500   INSERT("gcciphers", gcciphers());
3501   INSERT("GCAEAD", gcaead_pytype);
3502   INSERT("GAEKey", gaeadkey_pytype);
3503   INSERT("GAEAADClass", gcaeadaad_pytype);
3504   INSERT("GAEAAD", gaeadaad_pytype);
3505   INSERT("GAEEncClass", gcaeadenc_pytype);
3506   INSERT("GAEEnc", gaeadenc_pytype);
3507   INSERT("GAEDecClass", gcaeaddec_pytype);
3508   INSERT("GAEDec", gaeaddec_pytype);
3509   INSERT("gcaeads", gcaeads());
3510   INSERT("GCHash", gchash_pytype);
3511   INSERT("GHash", ghash_pytype);
3512   INSERT("gchashes", d = gchashes());
3513   sha_pyobj = PyDict_GetItemString(d, "sha"); Py_INCREF(sha_pyobj);
3514   has160_pyobj = PyDict_GetItemString(d, "has160"); Py_INCREF(has160_pyobj);
3515   INSERT("GCMAC", gcmac_pytype);
3516   INSERT("GMAC", gmac_pytype);
3517   INSERT("GMACHash", gmhash_pytype);
3518   INSERT("gcmacs", gcmacs());
3519   INSERT("Poly1305Class", poly1305cls_pytype);
3520   INSERT("poly1305", poly1305key_pytype);
3521   INSERT("Poly1305Hash", poly1305hash_pytype);
3522   INSERT("Keccak1600", kxvik_pytype);
3523   INSERT("Shake", shake_pytype);
3524   INSERT("Shake128", shake128_pytype);
3525   INSERT("Shake256", shake256_pytype);
3526   INSERT("GCPRP", gcprp_pytype);
3527   INSERT("GPRP", gprp_pytype);
3528   INSERT("gcprps", gcprps());
3529 }
3530
3531 /*----- That's all, folks -------------------------------------------------*/