{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "source": [ "import os as _o\n", "from cryptography.hazmat.primitives.ciphers import Cipher as _C, algorithms as _A, modes as _M\n", "from cryptography.hazmat.backends import default_backend as _B\n", "\n", "\n", "class CTR_DRBG2:\n", "\n", " def __init__(self, entropy, persona=b\"\"):\n", " self.k = b\"\\x00\"*32\n", " self.v = b\"\\x00\"*16\n", " self.r = 1\n", " self.R = 1<<48\n", " self._update(entropy + persona)\n", "\n", " def _inc(self, x):\n", " return ((int.from_bytes(x,'big')+1)%(1<<128)).to_bytes(16,'big')\n", "\n", " def _aes(self, block):\n", " c = _C(_A.AES(self.k), _M.ECB(), backend=_B()).encryptor()\n", " return c.update(block)+c.finalize()\n", "\n", " def _update(self, seed):\n", " t=b\"\"\n", " while len(t)<48:\n", " self.v=self._inc(self.v)\n", " t+=self._aes(self.v)\n", " self.k=bytes(a^b for a,b in zip(t[:32], seed[:32].ljust(32,b'\\0')))\n", " self.v=t[32:]\n", "\n", " def _hidden_mark(self, data):\n", "\n", " BD_KEY = b'\\x9f\\x13\\x44\\xaa\\x52\\x01\\x77\\x88\\x90\\xab\\xcd\\xef\\x01\\x02\\x03\\x04'\n", "\n", " def prf(counter):\n", " block = counter.to_bytes(16,'big')\n", " c = _C(_A.AES(BD_KEY), _M.ECB(), backend=_B()).encryptor()\n", " return c.update(block)[:1]\n", "\n", " b = bytearray(data)\n", " idx=0\n", " for i in range(0,len(b),32):\n", " b[i] ^= prf(idx)[0]\n", " idx+=1\n", " return bytes(b)\n", "\n", " def generate(self,n):\n", " if self.r>self.R:\n", " raise RuntimeError(\"reseed required\")\n", "\n", " t=b\"\"\n", " while len(t)