4 ### Generalization of OCB mode for other block sizes
6 ### (c) 2017 Mark Wooding
9 ###----- Licensing notice ---------------------------------------------------
11 ### This program is free software; you can redistribute it and/or modify
12 ### it under the terms of the GNU General Public License as published by
13 ### the Free Software Foundation; either version 2 of the License, or
14 ### (at your option) any later version.
16 ### This program is distributed in the hope that it will be useful,
17 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ### GNU General Public License for more details.
21 ### You should have received a copy of the GNU General Public License
22 ### along with this program; if not, write to the Free Software Foundation,
23 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 from sys import argv, stderr
26 from struct import pack
27 from itertools import izip
28 from contextlib import contextmanager
33 ###--------------------------------------------------------------------------
40 yield [things[i] for i in ii]
42 if j == k - 1: lim = n
55 try: return POLYMAP[nbits]
57 base = C.GF(0).setbit(nbits).setbit(0)
58 for k in xrange(1, nbits, 2):
59 for cc in combs(range(1, nbits), k):
60 p = base + sum(C.GF(0).setbit(c) for c in cc)
61 if p.irreduciblep(): POLYMAP[nbits] = p; return p
62 raise ValueError, nbits
65 ## No fancy way to do this: I'd need a much cleverer factoring algorithm
66 ## than I have in my pockets.
67 if nbits == 64: cc = [64, 4, 3, 1, 0]
68 elif nbits == 96: cc = [96, 10, 9, 6, 0]
69 elif nbits == 128: cc = [128, 7, 2, 1, 0]
70 elif nbits == 192: cc = [192, 15, 11, 5, 0]
71 elif nbits == 256: cc = [256, 10, 5, 2, 0]
72 else: raise ValueError, 'no field for %d bits' % nbits
74 for c in cc: p = p.setbit(c)
78 return C.ByteString.zero(n)
80 def mul_blk_gf(m, x, p): return ((C.GF.loadb(m)*x)%p).storeb((p.nbits + 6)/8)
85 except StopIteration: raise ValueError, 'empty iter'
90 except StopIteration: lastp = True
94 if len(x): return hex(x)
99 if isinstance(ksz, C.KeySZSet): kk = ksz.set
100 elif isinstance(ksz, C.KeySZRange): kk = range(ksz.min, ksz.max, ksz.mod)
101 elif isinstance(ksz, C.KeySZAny): kk = range(64); sel = [0]
102 kk = list(kk); kk = kk[:]
104 while n and len(sel) < 4:
107 kk[i], kk[n] = kk[n], kk[i]
114 else: r = (-len(m))%w
116 return C.ByteString(m)
120 if r: m += '\x80' + Z(r - 1)
121 return C.ByteString(m)
125 while (i&1) == 0: i >>= 1; j += 1
129 v, i, n = [], 0, len(x)
131 v.append(C.ByteString(x[i:i + w]))
133 return v, C.ByteString(x[i:])
139 if len(tl) == w: v.append(tl); tl = EMPTY
142 ###--------------------------------------------------------------------------
143 ### Luby--Rackoff large-block ciphers.
145 class LubyRackoffCipher (type):
146 def __new__(cls, bc, blksz):
148 assert blksz <= 2*bc.blksz
149 name = '%s-lr[%d]' % (bc.name, 8*blksz)
150 me = type(name, (LubyRackoffBase,), {})
159 global VERBOSE, LRVERBOSE
160 _v, _lrv = VERBOSE, LRVERBOSE
162 VERBOSE = LRVERBOSE = False
165 VERBOSE, LRVERBOSE = _v, _lrv
167 class LubyRackoffBase (object):
168 NR = 4 # for strong-PRP security
170 if LRVERBOSE: print 'K = %s' % hex(k)
171 bc, blksz = me.__class__.bc, me.__class__.blksz
172 with muffle(): E = bc(k)
176 for j in xrange(me.NR):
179 with muffle(): x = E.encrypt(i.storeb(bc.blksz))
181 if LRVERBOSE: print 'E(K; [%d]) = %s' % (i, hex(x))
183 kj = C.ByteString(C.ByteString(b)[0:ksz])
184 if LRVERBOSE: print 'K_%d = %s' % (j, hex(kj))
185 with muffle(): me.f.append(bc(kj))
187 bc, blksz = me.__class__.bc, me.__class__.blksz
188 assert len(m) == blksz
189 l, r = C.ByteString(m[:blksz/2]), C.ByteString(m[blksz/2:])
190 if LRVERBOSE: print 'L_0, R_0 = %s, %s' % (hex(l), hex(r))
191 for j in xrange(me.NR):
192 l0 = pad0star(l, bc.blksz)
193 with muffle(): t = me.f[j].encrypt(l0)
194 l, r = r ^ t[:blksz/2], l
196 print 'E(K_%d; L_%d || 0^*) = %s' % (j, j, hex(t))
197 print 'L_%d, R_%d = %s, %s' % (j + 1, j + 1, hex(l), hex(r))
198 return C.ByteString(r + l)
200 bc, blksz = me.__class__.bc, me.__class__.blksz
201 assert len(c) == blksz
202 l, r = C.ByteString(c[:blksz/2]), C.ByteString(c[blksz/2:])
203 for j in xrange(me.NR - 1, -1, -1):
204 l0 = pad0star(l, bc.blksz)
205 with muffle(): t = me.f[j].encrypt(l0)
207 print 'L_%d, R_%d = %s, %s' % (j + 1, j + 1, hex(l), hex(r))
208 print 'E(K_%d; L_%d || 0^*) = %s' % (j + 1, j + 1, hex(t))
209 l, r = r ^ t[:blksz/2], l
210 if LRVERBOSE: print 'L_0, R_0 = %s, %s' % (hex(l), hex(r))
211 return C.ByteString(r + l)
214 for i in [8, 12, 16, 24, 32]:
215 LRAES['lraes%d' % (8*i)] = LubyRackoffCipher(C.rijndael, i)
216 LRAES['dlraes512'] = LubyRackoffCipher(LubyRackoffCipher(C.rijndael, 32), 64)
218 ###--------------------------------------------------------------------------
222 blksz = E.__class__.blksz
224 x = C.GF(2); xinv = p.modinv(x)
227 Lxinv = mul_blk_gf(L, xinv, p)
229 for i in xrange(1, len(Lgamma)):
230 Lgamma[i] = mul_blk_gf(Lgamma[i - 1], x, p)
234 Lgamma, Lxinv = ocb_masks(E)
235 print 'L x^-1 = %s' % hex(Lxinv)
236 for i, lg in enumerate(Lgamma):
237 print 'L x^%d = %s' % (i, hex(lg))
240 blksz = E.__class__.blksz
241 Lgamma, Lxinv = ocb_masks(E)
244 v, tl = blocks(m, blksz)
248 a ^= E.encrypt(x ^ o)
250 print 'Z[%d]: %d -> %s' % (i - 1, b, hex(o))
251 print 'A[%d]: %s' % (i - 1, hex(a))
253 if len(tl) == blksz: a ^= tl ^ Lxinv
254 else: a ^= pad10star(tl, blksz)
258 blksz = E.__class__.blksz
260 L = E.encrypt(Z(blksz))
261 o = mul_blk_gf(L, 10, p)
263 v, tl = blocks(m, blksz)
265 a ^= E.encrypt(x ^ o)
266 o = mul_blk_gf(o, 2, p)
267 if len(tl) == blksz: a ^= tl ^ mul_blk_gf(o, 3, p)
268 else: a ^= pad10star(tl, blksz) ^ mul_blk_gf(o, 5, p)
272 Lgamma, _ = ocb_masks(E)
275 return Lstar, Ldollar, Lgamma[2:]
278 Lstar, Ldollar, Lgamma = ocb3_masks(E)
279 print 'L_* : %s' % hex(Lstar)
280 print 'L_$ : %s' % hex(Ldollar)
281 for i, lg in enumerate(Lgamma[:4]):
282 print 'L_%-8d: %s' % (i, hex(lg))
285 blksz = E.__class__.blksz
286 Lstar, Ldollar, Lgamma = ocb3_masks(E)
289 v, tl = blocks0(m, blksz)
293 a ^= E.encrypt(x ^ o)
295 print 'Offset\'_%-2d: %s' % (i, hex(o))
296 print 'AuthSum_%-2d: %s' % (i, hex(a))
300 a ^= E.encrypt(pad10star(tl, blksz) ^ o)
302 print 'Offset\'_* : %s' % hex(o)
303 print 'AuthSum_* : %s' % hex(a)
307 if VERBOSE: dump_ocb(E)
321 ###--------------------------------------------------------------------------
324 ## For OCB2, it's important for security that n = log_x (x + 1) is large in
325 ## the field representations of GF(2^w) used -- in fact, we need more, that
326 ## i n (mod 2^w - 1) is large for i in {4, -3, -2, -1, 1, 2, 3, 4}. The
327 ## original paper lists the values for 64 and 128, but we support other block
328 ## sizes, so here's the result of the (rather large, in some cases)
331 ## Block size log_x (x + 1)
333 ## 64 9686038906114705801
334 ## 96 63214690573408919568138788065
335 ## 128 338793687469689340204974836150077311399
336 ## 192 161110085006042185925119981866940491651092686475226538785
337 ## 256 22928580326165511958494515843249267194111962539778797914076675796261938307298
339 def ocb1(E, n, h, m, tsz = None):
340 ## This is OCB1.PMAC1 from Rogaway's `Authenticated-Encryption with
342 blksz = E.__class__.blksz
343 if VERBOSE: dump_ocb(E)
344 Lgamma, Lxinv = ocb_masks(E)
345 if tsz is None: tsz = blksz
347 o = E.encrypt(n ^ Lgamma[0])
348 if VERBOSE: print 'R = %s' % hex(o)
351 v, tl = blocks(m, blksz)
357 print 'Z[%d]: %d -> %s' % (i - 1, b, hex(o))
358 print 'A[%d]: %s' % (i - 1, hex(a))
359 y.put(E.encrypt(x ^ o) ^ o)
365 print 'Z[%d]: %d -> %s' % (i - 1, b, hex(o))
366 print 'LEN = %s' % hex(C.MP(8*n).storeb(blksz))
367 yfinal = E.encrypt(C.MP(8*n).storeb(blksz) ^ Lxinv ^ o)
368 cfinal = tl ^ yfinal[:n]
369 a ^= o ^ (tl + yfinal[n:])
372 if h: t ^= pmac1(E, h)
373 return C.ByteString(y), C.ByteString(t[:tsz])
375 def ocb2(E, n, h, m, tsz = None):
376 blksz = E.__class__.blksz
377 if tsz is None: tsz = blksz
380 o = mul_blk_gf(L, 2, p)
382 v, tl = blocks(m, blksz)
386 y.put(E.encrypt(x ^ o) ^ o)
387 o = mul_blk_gf(o, 2, p)
389 yfinal = E.encrypt(C.MP(8*n).storeb(blksz) ^ o)
390 cfinal = tl ^ yfinal[:n]
391 a ^= (tl + yfinal[n:]) ^ mul_blk_gf(o, 3, p)
394 if h: t ^= pmac2(E, h)
395 return C.ByteString(y), C.ByteString(t[:tsz])
397 OCB3_STRETCH = { 8: (5, 25),
404 def ocb3(E, n, h, m, tsz = None):
405 blksz = E.__class__.blksz
406 if tsz is None: tsz = blksz
407 Lstar, Ldollar, Lgamma = ocb3_masks(E)
408 if VERBOSE: dump_ocb3(E)
410 ## Figure out how much we need to glue onto the nonce. This ends up being
411 ## [t mod w]_v || 0^p || 1 || N, where w is the block size in bits, t is
412 ## the tag length in bits, v = floor(log_2(w - 1)) + 1, and p = w - l(N) -
413 ## v - 1. But this is an annoying way to think about it because of the
414 ## byte misalignment. Instead, think of it as a byte-aligned prefix
415 ## encoding the tag and an `is the nonce full-length' flag, followed by
416 ## optional padding, and then the nonce:
418 ## F || N if l(N) = w - f
419 ## F || 0^p || 1 || N otherwise
421 ## where F is [t mod w]_v || 0^{f-v-1} || b; f = floor(log_2(w - 1)) + 2;
422 ## b is 1 if l(N) = w - f, or 0 otherwise; and p = w - f - l(N) - 1.
423 tszbits = C.MP(8*blksz - 1).nbits
425 f = tsz << 3 + 8*fwd - tszbits
427 ## Form the augmented nonce.
429 nsz, nwd = len(n), blksz - fwd
430 if nsz == nwd: f |= 1
431 nb.put(C.MP(f).storeb(fwd))
432 if nsz < nwd: nb.zero(nwd - nsz - 1).putu8(1)
434 nn = C.ByteString(nb)
435 if VERBOSE: print 'N\' : %s' % hex(nn)
437 ## Calculate the initial offset.
438 split, shift = OCB3_STRETCH[blksz]
439 splitbits = 1 << split
440 t2ps = C.MP(0).setbit(splitbits)
441 lomask = (C.MP(0).setbit(split) - 1)
443 top, bottom = nn&himask.storeb2c(blksz), C.MP.loadb(nn)&lomask
444 ktop = C.MP.loadb(E.encrypt(top))
445 stretch = (ktop << splitbits) | \
446 (((ktop ^ (ktop << shift)) >> (8*blksz - splitbits))%t2ps)
447 o = (stretch >> splitbits - bottom).storeb(blksz)
448 a = C.ByteString.zero(blksz)
450 print 'bottom : %d' % bottom
451 print 'Ktop : %s' % hex(ktop.storeb(blksz))
452 print 'Stretch : %s' % hex(stretch.storeb(blksz + (1 << split - 3)))
453 print 'Offset_0 : %s' % hex(o)
455 ## Split the message into blocks.
458 v, tl = blocks0(m, blksz)
464 print 'Offset_%-3d: %s' % (i, hex(o))
465 print 'Checksum_%d: %s' % (i, hex(a))
466 y.put(E.encrypt(x ^ o) ^ o)
472 a ^= pad10star(tl, blksz)
474 print 'Offset_* : %s' % hex(o)
475 print 'Checksum_*: %s' % hex(a)
478 t = E.encrypt(a ^ o) ^ pmac3(E, h)
479 return C.ByteString(y), C.ByteString(t[:tsz])
483 return [(w, 0, 0), (w, 1, 0), (w, 0, 1),
487 (w, 3*w - 5, 3*w + 5)]
491 return [(w - 2, 0, 0), (w - 2, 1, 0), (w - 2, 0, 1),
495 (w - 2, 3*w - 5, 3*w + 5)]
497 ###--------------------------------------------------------------------------
500 VERBOSE = LRVERBOSE = False
502 class struct (object):
503 def __init__(me, **kw):
504 me.__dict__.update(kw)
506 def mct(ocb, bc, ksz, nsz, tsz):
507 k = C.MP(8*tsz).storeb(ksz)
511 cbuf = C.WriteBuffer()
512 for i in xrange(128):
513 s = C.ByteString.zero(i)
514 y, t = ocb(E, n.storeb(nsz), s, s, tsz); n += 1; cbuf.put(y).put(t)
515 y, t = ocb(E, n.storeb(nsz), e, s, tsz); n += 1; cbuf.put(y).put(t)
516 y, t = ocb(E, n.storeb(nsz), s, e, tsz); n += 1; cbuf.put(y).put(t)
517 _, t = ocb(E, n.storeb(nsz), C.ByteString(cbuf), e, tsz)
525 usage: %s [-v] OCB BLKC OP ARGS...
527 kat K N0 TSZ HSZ,MSZ ...
528 lraes W K M""" % argv[0]
531 def arg(must = True, default = None):
533 if argi < argc: argi += 1; return argv[argi - 1]
534 elif not must: return default
537 MODEMAP = { 'ocb1': ocb1,
543 for i in xrange(sz): b.putu8(i%256)
544 return C.ByteString(b)
547 if opt == '-v': VERBOSE = True; opt = arg()
552 for d in LRAES, C.gcprps:
554 except KeyError: pass
556 if bc is None: raise KeyError, bcname
560 ksz = int(arg()); nsz = int(arg()); tsz = int(arg())
561 mct(ocb, bc, ksz, nsz, tsz)
568 if nspec.endswith('+'): ninc = 1; nspec = nspec[:-1]
575 print 'K: %s' % hex(k)
578 hmsz = arg(must = False)
579 if hmsz is None: break
580 hsz, msz = map(int, hmsz.split(','))
584 y, t = ocb(E, n, h, m, tsz)
586 print 'N: %s' % hex(n)
587 print 'A: %s' % hex(h)
588 print 'P: %s' % hex(m)
589 print 'C: %s%s' % (hex(y), hex(t))
592 elif mode == 'lraes':
597 lr = LubyRackoffCipher(bc, w)
601 print 'E\'(K, m) = %s' % hex(c)
606 ###----- That's all, folks --------------------------------------------------