acdd9979e858fa300b31f1d9de2830105b7e439e
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
32 ###--------------------------------------------------------------------------
39 yield [things
[i
] for i
in ii
]
41 if j
== k
- 1: lim
= n
54 try: return POLYMAP
[nbits
]
56 base
= C
.GF(0).setbit(nbits
).setbit(0)
57 for k
in xrange(1, nbits
, 2):
58 for cc
in combs(range(1, nbits
), k
):
59 p
= base
+ sum(C
.GF(0).setbit(c
) for c
in cc
)
60 if p
.irreduciblep(): POLYMAP
[nbits
] = p
; return p
61 raise ValueError, nbits
64 ## No fancy way to do this: I'd need a much cleverer factoring algorithm
65 ## than I have in my pockets.
66 if nbits
== 64: cc
= [64, 4, 3, 1, 0]
67 elif nbits
== 96: cc
= [96, 10, 9, 6, 0]
68 elif nbits
== 128: cc
= [128, 7, 2, 1, 0]
69 elif nbits
== 192: cc
= [192, 15, 11, 5, 0]
70 elif nbits
== 256: cc
= [256, 10, 5, 2, 0]
71 else: raise ValueError, 'no field for %d bits' % nbits
73 for c
in cc
: p
= p
.setbit(c
)
77 return C
.ByteString
.zero(n
)
79 def mul_blk_gf(m
, x
, p
): return ((C
.GF
.loadb(m
)*x
)%p
).storeb((p
.nbits
+ 6)/8)
84 except StopIteration: raise ValueError, 'empty iter'
89 except StopIteration: lastp
= True
93 if len(x
): return hex(x
)
98 if isinstance(ksz
, C
.KeySZSet
): kk
= ksz
.set
99 elif isinstance(ksz
, C
.KeySZRange
): kk
= range(ksz
.min, ksz
.max, ksz
.mod
)
100 elif isinstance(ksz
, C
.KeySZAny
): kk
= range(64); sel
= [0]
101 kk
= list(kk
); kk
= kk
[:]
103 while n
and len(sel
) < 4:
106 kk
[i
], kk
[n
] = kk
[n
], kk
[i
]
113 else: r
= (-len(m
))%w
115 return C
.ByteString(m
)
119 if r
: m
+= '\x80' + Z(r
- 1)
120 return C
.ByteString(m
)
124 while (i
&1) == 0: i
>>= 1; j
+= 1
128 v
, i
, n
= [], 0, len(x
)
130 v
.append(C
.ByteString(x
[i
:i
+ w
]))
132 return v
, C
.ByteString(x
[i
:])
138 if len(tl
) == w
: v
.append(tl
); tl
= EMPTY
141 ###--------------------------------------------------------------------------
142 ### Luby--Rackoff large-block ciphers.
144 class LubyRackoffCipher (type):
145 def __new__(cls
, bc
, blksz
):
147 assert blksz
<= 2*bc
.blksz
148 name
= '%s-lr[%d]' %
(bc
.name
, 8*blksz
)
149 me
= type(name
, (LubyRackoffBase
,), {})
156 class LubyRackoffBase (object):
157 NR
= 4 # for strong-PRP security
159 if LRVERBOSE
: print 'K = %s' %
hex(k
)
160 bc
, blksz
= me
.__class__
.bc
, me
.__class__
.blksz
165 for j
in xrange(me
.NR
):
168 x
= E
.encrypt(i
.storeb(bc
.blksz
))
170 if LRVERBOSE
: print 'E(K; [%d]) = %s' %
(i
, hex(x
))
172 kj
= C
.ByteString(C
.ByteString(b
)[0:ksz
])
173 if LRVERBOSE
: print 'K_%d = %s' %
(j
, hex(kj
))
176 bc
, blksz
= me
.__class__
.bc
, me
.__class__
.blksz
177 assert len(m
) == blksz
178 l
, r
= C
.ByteString(m
[:blksz
/2]), C
.ByteString(m
[blksz
/2:])
179 if LRVERBOSE
: print 'L_0, R_0 = %s, %s' %
(hex(l
), hex(r
))
180 for j
in xrange(me
.NR
):
181 l0
= pad0star(l
, bc
.blksz
)
182 t
= me
.f
[j
].encrypt(l0
)
183 l
, r
= r ^ t
[:blksz
/2], l
185 print 'E(K_%d; L_%d || 0^*) = %s' %
(j
, j
, hex(t
))
186 print 'L_%d, R_%d = %s, %s' %
(j
+ 1, j
+ 1, hex(l
), hex(r
))
187 return C
.ByteString(r
+ l
)
189 bc
, blksz
= me
.__class__
.bc
, me
.__class__
.blksz
190 assert len(c
) == blksz
191 l
, r
= C
.ByteString(c
[:blksz
/2]), C
.ByteString(c
[blksz
/2:])
192 for j
in xrange(me
.NR
- 1, -1, -1):
193 l0
= pad0star(l
, bc
.blksz
)
194 t
= me
.f
[j
].encrypt(l0
)
196 print 'L_%d, R_%d = %s, %s' %
(j
+ 1, j
+ 1, hex(l
), hex(r
))
197 print 'E(K_%d; L_%d || 0^*) = %s' %
(j
+ 1, j
+ 1, hex(t
))
198 l
, r
= r ^ t
[:blksz
/2], l
199 if LRVERBOSE
: print 'L_0, R_0 = %s, %s' %
(hex(l
), hex(r
))
200 return C
.ByteString(r
+ l
)
203 for i
in [8, 12, 16, 24, 32]:
204 LRAES
['lraes%d' %
(8*i
)] = LubyRackoffCipher(C
.rijndael
, i
)
206 ###--------------------------------------------------------------------------
210 blksz
= E
.__class__
.blksz
212 x
= C
.GF(2); xinv
= p
.modinv(x
)
215 Lxinv
= mul_blk_gf(L
, xinv
, p
)
217 for i
in xrange(1, len(Lgamma
)):
218 Lgamma
[i
] = mul_blk_gf(Lgamma
[i
- 1], x
, p
)
222 Lgamma
, Lxinv
= ocb_masks(E
)
223 print 'L x^-1 = %s' %
hex(Lxinv
)
224 for i
, lg
in enumerate(Lgamma
):
225 print 'L x^%d = %s' %
(i
, hex(lg
))
228 blksz
= E
.__class__
.blksz
229 Lgamma
, Lxinv
= ocb_masks(E
)
232 v
, tl
= blocks(m
, blksz
)
236 a ^
= E
.encrypt(x ^ o
)
238 print 'Z[%d]: %d -> %s' %
(i
- 1, b
, hex(o
))
239 print 'A[%d]: %s' %
(i
- 1, hex(a
))
241 if len(tl
) == blksz
: a ^
= tl ^ Lxinv
242 else: a ^
= pad10star(tl
, blksz
)
246 blksz
= E
.__class__
.blksz
248 L
= E
.encrypt(Z(blksz
))
249 o
= mul_blk_gf(L
, 10, p
)
251 v
, tl
= blocks(m
, blksz
)
253 a ^
= E
.encrypt(x ^ o
)
254 o
= mul_blk_gf(o
, 2, p
)
255 if len(tl
) == blksz
: a ^
= tl ^
mul_blk_gf(o
, 3, p
)
256 else: a ^
= pad10star(tl
, blksz
) ^
mul_blk_gf(o
, 5, p
)
260 Lgamma
, _
= ocb_masks(E
)
263 return Lstar
, Ldollar
, Lgamma
[2:]
266 Lstar
, Ldollar
, Lgamma
= ocb3_masks(E
)
267 print 'L_* : %s' %
hex(Lstar
)
268 print 'L_$ : %s' %
hex(Ldollar
)
269 for i
, lg
in enumerate(Lgamma
[:4]):
270 print 'L_%-8d: %s' %
(i
, hex(lg
))
273 blksz
= E
.__class__
.blksz
274 Lstar
, Ldollar
, Lgamma
= ocb3_masks(E
)
277 v
, tl
= blocks0(m
, blksz
)
281 a ^
= E
.encrypt(x ^ o
)
283 print 'Offset\'_%-2d: %s' %
(i
, hex(o
))
284 print 'AuthSum_%-2d: %s' %
(i
, hex(a
))
288 a ^
= E
.encrypt(pad10star(tl
, blksz
) ^ o
)
290 print 'Offset\'_* : %s' %
hex(o
)
291 print 'AuthSum_* : %s' %
hex(a
)
295 if VERBOSE
: dump_ocb(E
)
309 ###--------------------------------------------------------------------------
312 ## For OCB2, it's important for security that n = log_x (x + 1) is large in
313 ## the field representations of GF(2^w) used -- in fact, we need more, that
314 ## i n (mod 2^w - 1) is large for i in {4, -3, -2, -1, 1, 2, 3, 4}. The
315 ## original paper lists the values for 64 and 128, but we support other block
316 ## sizes, so here's the result of the (rather large, in some cases)
319 ## Block size log_x (x + 1)
321 ## 64 9686038906114705801
322 ## 96 63214690573408919568138788065
323 ## 128 338793687469689340204974836150077311399
324 ## 192 161110085006042185925119981866940491651092686475226538785
325 ## 256 22928580326165511958494515843249267194111962539778797914076675796261938307298
327 def ocb1(E
, n
, h
, m
, tsz
= None):
328 ## This is OCB1.PMAC1 from Rogaway's `Authenticated-Encryption with
330 blksz
= E
.__class__
.blksz
331 if VERBOSE
: dump_ocb(E
)
332 Lgamma
, Lxinv
= ocb_masks(E
)
333 if tsz
is None: tsz
= blksz
335 o
= E
.encrypt(n ^ Lgamma
[0])
336 if VERBOSE
: print 'R = %s' %
hex(o
)
339 v
, tl
= blocks(m
, blksz
)
345 print 'Z[%d]: %d -> %s' %
(i
- 1, b
, hex(o
))
346 print 'A[%d]: %s' %
(i
- 1, hex(a
))
347 y
.put(E
.encrypt(x ^ o
) ^ o
)
353 print 'Z[%d]: %d -> %s' %
(i
- 1, b
, hex(o
))
354 print 'LEN = %s' %
hex(C
.MP(8*n
).storeb(blksz
))
355 yfinal
= E
.encrypt(C
.MP(8*n
).storeb(blksz
) ^ Lxinv ^ o
)
356 cfinal
= tl ^ yfinal
[:n
]
357 a ^
= o ^
(tl
+ yfinal
[n
:])
360 if h
: t ^
= pmac1(E
, h
)
361 return C
.ByteString(y
), C
.ByteString(t
[:tsz
])
363 def ocb2(E
, n
, h
, m
, tsz
= None):
364 blksz
= E
.__class__
.blksz
365 if tsz
is None: tsz
= blksz
368 o
= mul_blk_gf(L
, 2, p
)
370 v
, tl
= blocks(m
, blksz
)
374 y
.put(E
.encrypt(x ^ o
) ^ o
)
375 o
= mul_blk_gf(o
, 2, p
)
377 yfinal
= E
.encrypt(C
.MP(8*n
).storeb(blksz
) ^ o
)
378 cfinal
= tl ^ yfinal
[:n
]
379 a ^
= (tl
+ yfinal
[n
:]) ^
mul_blk_gf(o
, 3, p
)
382 if h
: t ^
= pmac2(E
, h
)
383 return C
.ByteString(y
), C
.ByteString(t
[:tsz
])
385 OCB3_STRETCH
= { 8: (5, 25),
391 def ocb3(E
, n
, h
, m
, tsz
= None):
392 blksz
= E
.__class__
.blksz
393 if tsz
is None: tsz
= blksz
394 Lstar
, Ldollar
, Lgamma
= ocb3_masks(E
)
395 if VERBOSE
: dump_ocb3(E
)
397 ## Figure out how much we need to glue onto the nonce. This ends up being
398 ## [t mod w]_v || 0^p || 1 || N, where w is the block size in bits, t is
399 ## the tag length in bits, v = floor(log_2(w - 1)) + 1, and p = w - l(N) -
400 ## v - 1. But this is an annoying way to think about it because of the
401 ## byte misalignment. Instead, think of it as a byte-aligned prefix
402 ## encoding the tag and an `is the nonce full-length' flag, followed by
403 ## optional padding, and then the nonce:
405 ## F || N if l(N) = w - f
406 ## F || 0^p || 1 || N otherwise
408 ## where F is [t mod w]_v || 0^{f-v-1} || b; f = floor(log_2(w - 1)) + 2;
409 ## b is 1 if l(N) = w - f, or 0 otherwise; and p = w - f - l(N) - 1.
410 tszbits
= C
.MP(8*blksz
- 1).nbits
412 f
= tsz
<< 3 + 8*fwd
- tszbits
414 ## Form the augmented nonce.
416 nsz
, nwd
= len(n
), blksz
- fwd
417 if nsz
== nwd
: f |
= 1
418 nb
.put(C
.MP(f
).storeb(fwd
))
419 if nsz
< nwd
: nb
.zero(nwd
- nsz
- 1).putu8(1)
421 nn
= C
.ByteString(nb
)
422 if VERBOSE
: print 'N\' : %s' %
hex(nn
)
424 ## Calculate the initial offset.
425 split
, shift
= OCB3_STRETCH
[blksz
]
426 splitbits
= 1 << split
427 t2ps
= C
.MP(0).setbit(splitbits
)
428 lomask
= (C
.MP(0).setbit(split
) - 1)
430 top
, bottom
= nn
&himask
.storeb2c(blksz
), C
.MP
.loadb(nn
)&lomask
431 ktop
= C
.MP
.loadb(E
.encrypt(top
))
432 stretch
= (ktop
<< splitbits
) | \
433 (((ktop ^
(ktop
<< shift
)) >> (8*blksz
- splitbits
))%t2ps
)
434 o
= (stretch
>> splitbits
- bottom
).storeb(blksz
)
435 a
= C
.ByteString
.zero(blksz
)
437 print 'bottom : %d' % bottom
438 print 'Ktop : %s' %
hex(ktop
.storeb(blksz
))
439 print 'Stretch : %s' %
hex(stretch
.storeb(blksz
+ (1 << split
- 3)))
440 print 'Offset_0 : %s' %
hex(o
)
442 ## Split the message into blocks.
445 v
, tl
= blocks0(m
, blksz
)
451 print 'Offset_%-3d: %s' %
(i
, hex(o
))
452 print 'Checksum_%d: %s' %
(i
, hex(a
))
453 y
.put(E
.encrypt(x ^ o
) ^ o
)
459 a ^
= pad10star(tl
, blksz
)
461 print 'Offset_* : %s' %
hex(o
)
462 print 'Checksum_*: %s' %
hex(a
)
465 t
= E
.encrypt(a ^ o
) ^
pmac3(E
, h
)
466 return C
.ByteString(y
), C
.ByteString(t
[:tsz
])
470 return [(w
, 0, 0), (w
, 1, 0), (w
, 0, 1),
474 (w
, 3*w
- 5, 3*w
+ 5)]
478 return [(w
- 2, 0, 0), (w
- 2, 1, 0), (w
- 2, 0, 1),
482 (w
- 2, 3*w
- 5, 3*w
+ 5)]
484 ###--------------------------------------------------------------------------
487 VERBOSE
= LRVERBOSE
= False
489 class struct (object):
490 def __init__(me
, **kw
):
491 me
.__dict__
.update(kw
)
493 def mct(ocb
, bc
, ksz
, nsz
, tsz
):
494 k
= C
.MP(8*tsz
).storeb(ksz
)
498 cbuf
= C
.WriteBuffer()
499 for i
in xrange(128):
500 s
= C
.ByteString
.zero(i
)
501 y
, t
= ocb(E
, n
.storeb(nsz
), s
, s
, tsz
); n
+= 1; cbuf
.put(y
).put(t
)
502 y
, t
= ocb(E
, n
.storeb(nsz
), e
, s
, tsz
); n
+= 1; cbuf
.put(y
).put(t
)
503 y
, t
= ocb(E
, n
.storeb(nsz
), s
, e
, tsz
); n
+= 1; cbuf
.put(y
).put(t
)
504 _
, t
= ocb(E
, n
.storeb(nsz
), C
.ByteString(cbuf
), e
, tsz
)
512 usage: %s [-v] OCB BLKC OP ARGS...
514 kat K N0 TSZ HSZ,MSZ ...
515 lraes W K M""" % argv
[0]
518 def arg(must
= True, default
= None):
520 if argi
< argc
: argi
+= 1; return argv
[argi
- 1]
521 elif not must
: return default
524 MODEMAP
= { 'ocb1': ocb1
,
530 for i
in xrange(sz
): b
.putu8(i
%256)
531 return C
.ByteString(b
)
534 if opt
== '-v': VERBOSE
= True; opt
= arg()
539 for d
in LRAES
, C
.gcprps
:
541 except KeyError: pass
543 if bc
is None: raise KeyError, bcname
547 ksz
= int(arg()); nsz
= int(arg()); tsz
= int(arg())
548 mct(ocb
, bc
, ksz
, nsz
, tsz
)
555 if nspec
.endswith('+'): ninc
= 1; nspec
= nspec
[:-1]
562 print 'K: %s' %
hex(k
)
565 hmsz
= arg(must
= False)
566 if hmsz
is None: break
567 hsz
, msz
= map(int, hmsz
.split(','))
571 y
, t
= ocb(E
, n
, h
, m
, tsz
)
573 print 'N: %s' %
hex(n
)
574 print 'A: %s' %
hex(h
)
575 print 'P: %s' %
hex(m
)
576 print 'C: %s%s' %
(hex(y
), hex(t
))
579 elif mode
== 'lraes':
584 lr
= LubyRackoffCipher(bc
, w
)
588 print 'E\'(K, m) = %s' %
hex(c
)
593 ###----- That's all, folks --------------------------------------------------