Eunchan Kim | 8e2587e | 2020-03-10 14:16:24 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | # Copyright lowRISC contributors. |
| 3 | # Licensed under the Apache License, Version 2.0, see LICENSE for details. |
| 4 | # SPDX-License-Identifier: Apache-2.0 |
| 5 | r"""Calculate Round Constant |
| 6 | """ |
| 7 | |
| 8 | import argparse |
| 9 | import bitarray as ba |
| 10 | import logging as log |
| 11 | |
| 12 | |
| 13 | def main(): |
| 14 | parser = argparse.ArgumentParser( |
| 15 | prog="keccak round constant generator", |
| 16 | description= |
| 17 | '''This tool generates the round constants based on the given max round number''' |
| 18 | ) |
| 19 | parser.add_argument( |
| 20 | '-r', |
| 21 | type=int, |
| 22 | default=24, |
| 23 | help='''Max Round value. Default is SHA3 Keccak round %(default)''') |
| 24 | parser.add_argument('--verbose', '-v', action='store_true', help='Verbose') |
| 25 | |
| 26 | args = parser.parse_args() |
| 27 | |
| 28 | if (args.verbose): |
| 29 | log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) |
| 30 | else: |
| 31 | log.basicConfig(format="%(levelname)s: %(message)s") |
| 32 | |
| 33 | if args.r < 1: |
| 34 | log.error("Max Round value should be greater than 0") |
| 35 | |
| 36 | # Create 0..255 bit array |
| 37 | rc = ba.bitarray(256) |
| 38 | rc.setall(0) |
| 39 | |
| 40 | r = ba.bitarray('10000000') |
| 41 | rc[0] = True # t%255 == 0 -> 1 |
| 42 | for i in range(1, 256): |
| 43 | # Update from t=1 to t=255 |
| 44 | r_d = ba.bitarray('0') + r |
| 45 | if r_d[8]: |
| 46 | #Flip 0,4,5,6 |
| 47 | r = r_d[0:8] ^ ba.bitarray('10001110') |
| 48 | else: |
| 49 | r = r_d[0:8] |
| 50 | |
| 51 | rc[i] = r[0] |
| 52 | |
| 53 | ## Print rc |
| 54 | print(rc) |
| 55 | |
| 56 | ## Round |
| 57 | |
| 58 | rcs = [] # Each entry represent the round |
| 59 | for rnd in range(0, args.r): |
| 60 | # Let RC=0 |
| 61 | rndconst = ba.bitarray(64) |
| 62 | rndconst.setall(0) |
| 63 | # for j [0 .. L] RC[2**j-1] = rc(j+7*rnd) |
| 64 | for j in range(0, 7): #0 to 6 |
| 65 | rndconst[2**j - 1] = rc[(j + 7 * rnd) % 255] |
| 66 | print("64'h{}, // Round {}".format(rndhex(rndconst), rnd)) |
| 67 | |
| 68 | |
| 69 | def rndhex(bit) -> str: |
| 70 | return bit[::-1].tobytes().hex() |
| 71 | |
| 72 | |
| 73 | if __name__ == "__main__": |
| 74 | main() |