1from __future__ import absolute_import
2# Written by Ross Cohen
3# Maintained by Chris Hutchinson
4# see LICENSE.txt for license information
5
6from builtins import chr
7from builtins import range
8from .entropy import string_to_long, long_to_string
9import sha
10
11def crypt(text, key, counter=0):
12    keylen, length = len(key), len(text)
13    pos, cyphertext = 0, []
14    while pos < length:
15        scounter = long_to_string(counter, keylen)
16        hash = sha.new("ctr mode crypt" + key + scounter).digest()
17        for i in range(min(length-pos, len(hash))):
18            cyphertext.append(chr(ord(hash[i]) ^ ord(text[pos])))
19            pos += 1
20        counter += 1
21    return (''.join(cyphertext), counter)
22