From 69e8136a3787bd2cd1a602791593bb40ad8661ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juhani=20Krekel=C3=A4?= Date: Wed, 24 Jun 2020 13:45:11 +0300 Subject: [PATCH] Unoptimized implementation of chacha20-poly1305 --- .gitignore | 2 + CC0 | 116 ++++++++++++++++++++++++++++++++++++++++++++++++ chacha20.py | 75 +++++++++++++++++++++++++++++++ chapoly_aead.py | 49 ++++++++++++++++++++ poly1305.py | 39 ++++++++++++++++ 5 files changed, 281 insertions(+) create mode 100644 .gitignore create mode 100644 CC0 create mode 100644 chacha20.py create mode 100644 chapoly_aead.py create mode 100644 poly1305.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bec372b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.swp +__pycache__ diff --git a/CC0 b/CC0 new file mode 100644 index 0000000..670154e --- /dev/null +++ b/CC0 @@ -0,0 +1,116 @@ +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + diff --git a/chacha20.py b/chacha20.py new file mode 100644 index 0000000..2e657f1 --- /dev/null +++ b/chacha20.py @@ -0,0 +1,75 @@ +def add(x, y): + return (x + y) & 0xffffffff + +def rotl(x, n): + return (x << n) & 0xffffffff | (x >> (32 - n)) + +def quarterround(a, b, c, d): + a = add(a, b) + d ^= a + d = rotl(d, 16) + + c = add(c, d) + b ^= c + b = rotl(b, 12) + + a = add(a, b) + d ^= a + d = rotl(d, 8) + + c = add(c, d) + b ^= c + b = rotl(b, 7) + + return a, b, c, d + +def u32(i): + a, b, c, d = i + return a | (b << 8) | (c << 16) | (d << 24) + +def unu32(n): + return bytes((n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, n >> 24)) + +def chacha20_block(key, counter, nonce): + s = [ + 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, + u32(key[:4]), u32(key[4:8]), u32(key[8:12]), u32(key[12:16]), + u32(key[16:20]), u32(key[20:24]), u32(key[24:28]), u32(key[28:]), + counter, u32(nonce[:4]), u32(nonce[4:8]), u32(nonce[8:]) + ] + initial = s[:] + + def qr(i, j, k, l): + s[i], s[j], s[k], s[l] = quarterround(s[i], s[j], s[k], s[l]) + for _ in range(10): + qr(0, 4, 8, 12) + qr(1, 5, 9, 13) + qr(2, 6, 10, 14) + qr(3, 7, 11, 15) + qr(0, 5, 10, 15) + qr(1, 6, 11, 12) + qr(2, 7, 8, 13) + qr(3, 4, 9, 14) + + s = [add(initial[i], s[i]) for i in range(len(s))] + return b''.join(unu32(i) for i in s) + +def ceildiv(a, b): + return a // b if a % b == 0 else a // b + 1 + +def chacha20(key, counter, nonce, message): + for i in range(ceildiv(len(message), 64)): + keystream = chacha20_block(key, counter + i, nonce) + yield from (a ^ b for a, b in zip(message[i*64:i*64+64], keystream)) + +def prettyprint_state(s): + for i in range(4): + print('%08x %08x %08x %08x' % (s[i*4], s[i*4+1], s[i*4+2], s[i*4+3])) + print() + +if __name__ == '__main__': + key = bytes.fromhex('00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f'.replace(':','')) + nonce = bytes.fromhex('00:00:00:00:00:00:00:4a:00:00:00:00'.replace(':','')) + message = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it." + print(bytes(chacha20(key, 1, nonce, message)).hex() == '6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d807ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab77937365af90bbf74a35be6b40b8eedf2785e42874d') + diff --git a/chapoly_aead.py b/chapoly_aead.py new file mode 100644 index 0000000..75a6b18 --- /dev/null +++ b/chapoly_aead.py @@ -0,0 +1,49 @@ +import secrets + +import chacha20 +import poly1305 + +def unleu64(n): + assert n >> 64 == 0 + return bytes((n >> i) & 0xff for i in range(0, 64, 8)) + +def pad16(x): + if len(x) % 16 == 0: + return b'' + else: + return b'\x00' * (16 - (len(x) % 16)) + +def poly1305_key_gen(key, nonce): + return chacha20.chacha20_block(key, 0, nonce)[:32] + +def generate_tag(aad, key, nonce, ciphertext): + key = poly1305_key_gen(key, nonce) + message = b''.join(( + aad, pad16(aad), + ciphertext, pad16(ciphertext), + unleu64(len(aad)), + unleu64(len(ciphertext)) + )) + return poly1305.poly1305(message, key) + +def chapoly_aead_enc(aad, key, iv, constant, plaintext): + nonce = constant + iv + ciphertext = bytes(chacha20.chacha20(key, 1, nonce, plaintext)) + tag = generate_tag(aad, key, nonce, ciphertext) + return ciphertext + tag + +def chapoly_aead_dec(aad, key, iv, constant, ciphertext): + nonce = constant + iv + ciphertext, tag = ciphertext[:-16], ciphertext[-16:] + expected_tag = generate_tag(aad, key, nonce, ciphertext) + if not secrets.compare_digest(tag, expected_tag): + return None + return bytes(chacha20.chacha20(key, 1, nonce, ciphertext)) + +if __name__ == '__main__': + plaintext = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it." + aad = bytes.fromhex('50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7') + key = bytes.fromhex('80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f') + iv = b'@ABCDEFG' + constant = bytes.fromhex('07 00 00 00') + print(chapoly_aead_enc(aad, key, iv, constant, plaintext) == bytes.fromhex('d3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2 a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6 3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b 1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36 92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58 fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc 3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b 61 16 1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91'.replace(':',''))) diff --git a/poly1305.py b/poly1305.py new file mode 100644 index 0000000..76824d3 --- /dev/null +++ b/poly1305.py @@ -0,0 +1,39 @@ +def clamp(r): + r = bytearray(r) + r[3] &= 15 + r[7] &= 15 + r[11] &= 15 + r[15] &= 15 + r[4] &= 252 + r[8] &= 252 + r[12] &= 252 + return r + +def ceildiv(a, b): + return a // b if a % b == 0 else a // b + 1 + +def leu(b): + n = 0 + for i in range(len(b)): + n |= b[i] << (i * 8) + return n + +def unleu128(n): + return bytes((n >> i) & 0xff for i in range(0, 128, 8)) + +def poly1305(message, key): + r = leu(clamp(key[:16])) + s = leu(key[16:]) + P = 2**130 - 5 + acc = 0 + for i in range(ceildiv(len(message), 16)): + num = leu(message[i*16:i*16 + 16] + b'\x01') + # WARNING: This is most likely not timing-safe + acc = ((acc + num) * r) % P + acc += s + return unleu128(acc) + +if __name__ == '__main__': + key = bytes.fromhex('85:d6:be:78:57:55:6d:33:7f:44:52:fe:42:d5:06:a8:01:03:80:8a:fb:0d:b2:fd:4a:bf:f6:af:41:49:f5:1b'.replace(':', '')) + message = b'Cryptographic Forum Research Group' + print(poly1305(message, key).hex() == 'a8:06:1d:c1:30:51:36:c6:c2:2b:8b:af:0c:01:27:a9'.replace(':', ''))