k98kurz

xof_stream_cipher_b64.py

Jul 14th, 2021 (edited)
587
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.72 KB | None | 0 0
  1. """XOF Stream Cipher: encrypt and decrypt strings with shake256 - base64 version"""
  2.  
  3.  
  4. from base64 import b64encode, b64decode
  5. from hashlib import sha256, shake_256
  6. from secrets import token_bytes
  7. from sys import argv
  8.  
  9.  
  10. def xor(b1: bytes, b2: bytes) -> bytes:
  11.     """XOR two equal-length byte strings together."""
  12.     b3 = bytearray()
  13.     for i in range(len(b1)):
  14.         b3.append(b1[i] ^ b2[i])
  15.  
  16.     return bytes(b3)
  17.  
  18.  
  19. def derive_key(*parts: list[bytes]) -> bytes:
  20.     """Derives a one-time key from parts."""
  21.     pad = b''.join([sha256(p).digest() for p in parts])
  22.     return sha256(pad).digest()
  23.  
  24.  
  25. def encrypt(key: bytes, iv: bytes, plaintext: bytes) -> bytes:
  26.     """Stream cipher encrypt."""
  27.     key_bytes = shake_256(derive_key(key, iv, b'enc')).digest(len(plaintext))
  28.  
  29.     return xor(plaintext, key_bytes)
  30.  
  31.  
  32. def decrypt(key: bytes, iv: bytes, ciphertext: bytes) -> bytes:
  33.     """Stream cipher decrypt."""
  34.     key_bytes = shake_256(derive_key(key, iv, b'enc')).digest(len(ciphertext))
  35.  
  36.     return xor(ciphertext, key_bytes)
  37.  
  38.  
  39. def hmac(key: bytes, iv: bytes, message: bytes) -> bytes:
  40.     """Create an hmac according to rfc 2104 specifications."""
  41.     # set up variables
  42.     B = 136
  43.     ipad_byte = 0x36
  44.     opad_byte = 0x5c
  45.     null_byte = 0x00
  46.     ipad = bytes([ipad_byte] * B)
  47.     opad = bytes([opad_byte] * B)
  48.  
  49.     key = derive_key(key, iv, b'mac')
  50.  
  51.     # pad key with null bytes
  52.     key = key + bytes([null_byte] * (B - len(key)))
  53.  
  54.     # compute and return the hmac
  55.     partial = sha256(xor(key, ipad) + message).digest()
  56.     return sha256(xor(key, opad) + partial).digest()
  57.  
  58.  
  59. def check_hmac(key: bytes, iv: bytes, message: bytes, mac: bytes) -> bool:
  60.     """Check an hmac."""
  61.     # first compute the proper hmac
  62.     computed = hmac(key, iv, message)
  63.  
  64.     # if it is the wrong length, reject
  65.     if len(mac) != len(computed):
  66.         return False
  67.  
  68.     # compute difference without revealing anything through timing attack
  69.     diff = 0
  70.     for i in range(len(mac)):
  71.         diff += mac[i] ^ computed[i]
  72.  
  73.     return diff == 0
  74.  
  75.  
  76. def seal(key: bytes, plaintext: bytes, iv_size: int = 16) -> str:
  77.     """Generate an iv, encrypt a message, and create an hmac all in one."""
  78.     iv = token_bytes(iv_size)
  79.     ct = encrypt(key, iv, plaintext)
  80.     return (
  81.         b64encode(iv) + b'.' + b64encode(ct) + b'.' + b64encode(hmac(key, iv, ct))
  82.     ).decode()
  83.  
  84.  
  85. def unseal(key: bytes, ciphertext: str) -> bytes:
  86.     """Checks hmac, then decrypts the message."""
  87.     ciphertext = ciphertext.split('.')
  88.     iv = b64decode(ciphertext[0])
  89.     ct = b64decode(ciphertext[1])
  90.     ac = b64decode(ciphertext[2])
  91.  
  92.     if not check_hmac(key, iv, ct, ac):
  93.         raise Exception('HMAC authentication failed')
  94.  
  95.     return decrypt(key, iv, ct)
  96.  
  97.  
  98. def main(args):
  99.     """Main function for invoking as cli tool."""
  100.     # parse arguments
  101.     mode = args[0]
  102.     key = bytes(args[1], 'utf-8')
  103.     text = args[2]
  104.     iv = bytes(args[3], 'utf-8') if len(args) > 3 else None
  105.  
  106.     if mode == 'encrypt' or mode == 'e':
  107.         if iv is None:
  108.             return print('missing iv')
  109.         print(b64encode(encrypt(key, iv, bytes(text, 'utf-8'))).decode())
  110.     elif mode == 'decrypt' or mode == 'd':
  111.         if iv is None:
  112.             return print('missing iv')
  113.         print(decrypt(key, iv, b64decode(text)).decode())
  114.     elif mode == 'seal' or mode == 's':
  115.         print(seal(key, bytes(text, 'utf-8')))
  116.     elif mode == 'open' or mode == 'o':
  117.         print(unseal(key, text).decode())
  118.     else:
  119.         print('unknown mode: ' + mode)
  120.  
  121.  
  122. if __name__ == '__main__':
  123.     if len(argv) < 4:
  124.         print(
  125.             'usage: ' + argv[0] +
  126.             ' [encrypt|e|decrypt|d|seal|s|open|o] [key] [plaintext|ciphertext] [iv]'
  127.         )
  128.         print('\tiv - necessary for encrypt and decrypt, but not seal')
  129.         exit(1)
  130.     main(argv[1:])
  131.  
  132.  
  133. def license():
  134.     """Copyleft (c) 2026 k98kurz
  135.  
  136.        Permission to use, copy, modify, and/or distribute this software
  137.        for any purpose with or without fee is hereby granted, provided
  138.        that the above copyleft notice and this permission notice appear in
  139.        all copies.
  140.  
  141.        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  142.        WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  143.        WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  144.        AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  145.        CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  146.        OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  147.        NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  148.        CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  149.    """
  150.     return license.__doc__
Add Comment
Please, Sign In to add comment