| 113 | |
| 114 | |
| 115 | def encode(msg, pubkey, verbose=False): |
| 116 | chunksize = int(log(pubkey.modulus, 256)) |
| 117 | outchunk = chunksize + 1 |
| 118 | outfmt = '%%0%dx' % (outchunk * 2,) |
| 119 | bmsg = msg if isinstance(msg, binary_type) else msg.encode('utf-8') |
| 120 | result = [] |
| 121 | for start in range_func(0, len(bmsg), chunksize): |
| 122 | chunk = bmsg[start:start + chunksize] |
| 123 | chunk += b'\x00' * (chunksize - len(chunk)) |
| 124 | plain = int(hexlify(chunk), 16) |
| 125 | coded = pow(plain, *pubkey) |
| 126 | bcoded = unhexlify((outfmt % coded).encode()) |
| 127 | if verbose: |
| 128 | print('Encode:', chunksize, chunk, plain, coded, bcoded) |
| 129 | result.append(bcoded) |
| 130 | return b''.join(result) |
| 131 | |
| 132 | |
| 133 | def decode(bcipher, privkey, verbose=False): |