path
stringlengths 9
117
| type
stringclasses 2
values | project
stringclasses 10
values | commit_hash
stringlengths 40
40
| commit_message
stringlengths 1
137
| ground_truth
stringlengths 0
2.74k
| main_code
stringlengths 102
3.37k
| context
stringlengths 0
14.7k
|
---|---|---|---|---|---|---|---|
ciphey.Decryptor.Hash.hashBuster/theta
|
Modified
|
Ciphey~Ciphey
|
5c3a81c53c03bd60395e00f26c0bef5413865ec0
|
Implementing timeouts in hash busdter
|
<2>:<add> % (hashvalue, hashtype),
<del> % (hashvalue, hashtype)
<3>:<add> timeout=5,
|
# module: ciphey.Decryptor.Hash.hashBuster
def theta(hashvalue, hashtype):
<0> response = requests.get(
<1> "https://md5decrypt.net/Api/api.php?hash=%s&hash_type=%s&[email protected]&code=1152464b80a61728"
<2> % (hashvalue, hashtype)
<3> ).text
<4> if len(response) != 0:
<5> return response
<6> else:
<7> return False
<8>
|
===========changed ref 0===========
# module: ciphey.Decryptor.Hash.hashBuster
def gamma(hashvalue, hashtype):
+ response = requests.get(
+ "https://www.nitrxgen.net/md5db/" + hashvalue, timeout=5
- response = requests.get("https://www.nitrxgen.net/md5db/" + hashvalue).text
+ ).text
if response:
return response
else:
return False
===========changed ref 1===========
# module: ciphey.Decryptor.Hash.hashBuster
def beta(hashvalue, hashtype):
response = requests.get(
+ "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
- "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue
).text
match = re.search(r'/generate-hash/?text=.*?"', response)
if match:
return match.group(1)
else:
return False
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
5554d5f21336f4faef807330749d19a6f80cc8c1
|
Rich prob table now prints
|
<13>:<add> logger.debug(f"Sorting {key}")
<18>:<add> logger.debug(f"New max local found {maxLocal}")
<27>:<add> # this way, it should always work on most likely first.
<del> # this way, it should always work on most likely first.#
<28>:<add> logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> for key, value in probTable.items():
<13> maxLocal = 0
<14> # for each item in that table
<15> for key2, value2 in value.items():
<16> maxLocal = maxLocal + value2
<17> if maxLocal > maxOverall:
<18> # because the dict doesnt reset
<19> maxDictPair = {}
<20> maxOverall = maxLocal
<21> # so eventually, we get the maximum dict pairing?
<22> maxDictPair[key] = value
<23> highestKey = key
<24> # removes the highest key from the prob table
<25> del probTable[highestKey]
<26> # returns the max dict (at the start) with the prob table
<27> # this way, it should always work on most likely first.#
<28> d = {**maxDictPair, **probTable}
<29> logger.debug(f"The new sorted prob table is {d}")
<30> return d
<31>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
newSort(self, newDict)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
ciphey.mathsHelper/mathsHelper.newSort
|
Modified
|
Ciphey~Ciphey
|
5554d5f21336f4faef807330749d19a6f80cc8c1
|
Rich prob table now prints
|
<6>:<add> logger.debug(f"The old dictionary before newSort() is {newDict}")
<7>:<add> logger.debug(f"The dictionary after newSort() is {sortedI}")
|
# module: ciphey.mathsHelper
class mathsHelper:
def newSort(self, newDict):
<0> # gets the key of the dictionary
<1> # keyDict = list(newDict.keys())[0]
<2> # gets the items of that key (which is a dictionary)
<3> d = dict(newDict)
<4>
<5> # (f"d is {d}")
<6> sortedI = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
<7> # sortedI = sortDictionary(x)
<8> return sortedI
<9>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper.sortProbTable
maxDictPair[key] = value
maxDictPair = {}
del probTable[highestKey]
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
for key, value in probTable.items():
+ logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
maxLocal = maxLocal + value2
if maxLocal > maxOverall:
+ logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
# removes the highest key from the prob table
del probTable[highestKey]
# returns the max dict (at the start) with the prob table
+ # this way, it should always work on most likely first.
- # this way, it should always work on most likely first.#
+ logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
5554d5f21336f4faef807330749d19a6f80cc8c1
|
Rich prob table now prints
|
<24>:<add>
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<2> self.whatToChoose = {
<3> self.hash: {
<4> "sha1": self.probabilityDistribution[0],
<5> "md5": self.probabilityDistribution[1],
<6> "sha256": self.probabilityDistribution[2],
<7> "sha512": self.probabilityDistribution[3],
<8> },
<9> self.basic: {"caesar": self.probabilityDistribution[4]},
<10> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<11> self.encoding: {
<12> "reverse": self.probabilityDistribution[6],
<13> "base64": self.probabilityDistribution[7],
<14> "binary": self.probabilityDistribution[8],
<15> "hexadecimal": self.probabilityDistribution[9],
<16> "ascii": self.probabilityDistribution[10],
<17> "morse": self.probabilityDistribution[11],
<18> },
<19> }
<20>
<21> logger.debug(
<22> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<23> )
<24> # sorts each indiviudal sub-dictionary
<25> for key, value in self.whatToChoose.items():
<26> for k, v in value.items():
<27> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<28> if v < 0.01:
<29> self.whatToChoose[key][k] = 0.01
<30> logger.debug(
<31> f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
<32> )
<33>
<34> for key, value in self.whatToChoose.items():
<35> self.whatToChoose[key] = self.mh.</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# ok so this looks wacky but hear me out here
# a.update(b)
# adds all content of dict b onto end of dict a
# no way to add it to front, so I have to do this :)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go</s>
===========below chunk 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s>ryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
at: neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def newSort(self, newDict):
# gets the key of the dictionary
# keyDict = list(newDict.keys())[0]
# gets the items of that key (which is a dictionary)
d = dict(newDict)
# (f"d is {d}")
+ logger.debug(f"The old dictionary before newSort() is {newDict}")
sortedI = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
+ logger.debug(f"The dictionary after newSort() is {sortedI}")
# sortedI = sortDictionary(x)
return sortedI
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
for key, value in probTable.items():
+ logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
maxLocal = maxLocal + value2
if maxLocal > maxOverall:
+ logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
# removes the highest key from the prob table
del probTable[highestKey]
# returns the max dict (at the start) with the prob table
+ # this way, it should always work on most likely first.
- # this way, it should always work on most likely first.#
+ logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.__main__/Ciphey.produceProbTable
|
Modified
|
Ciphey~Ciphey
|
5554d5f21336f4faef807330749d19a6f80cc8c1
|
Rich prob table now prints
|
<9>:<add> self.console.print(table)
<12>:<add> for k, v in probTable.items():
<del> for key, value in probTable:
<13>:<add> for key, value in v.items():
<add> # Prevents the table from showing pointless 0.01 probs as they're faked
<add> if value == 0.01:
<add> continue
<add> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<add> val_as_percent = str(round(self.mh.percentage(value, 1), 2))
<del> valAsPercent = str(value * 100) + "%"
<14>:<add> keyStr = str(key).capitalize()
<del> keyStr = str(key)
<15>:<add> logger.debug(
<add> f"The value as percentage is {val_as_percent} and key is {keyStr}"
<add> )
<add> table.add_row(keyStr, val_as_percent)
<del> table.add_row(key, value)
|
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
<0> """Produces the probability table using Rich's API
<1>
<2> :probTable: the probability distribution table returned by the neural network
<3> :returns: Nothing, it prints out the prob table.
<4>
<5> """
<6> table = Table(show_header=True, header_style="bold magenta")
<7> table.add_column("Name of Cipher")
<8> table.add_column("Probability", justify="right")
<9> # for every key, value in dict add a row
<10> # I think key is self.caesarcipher and not "caesar cipher"
<11> # i must callName() somewhere else in this code
<12> for key, value in probTable:
<13> valAsPercent = str(value * 100) + "%"
<14> keyStr = str(key)
<15> table.add_row(key, value)
<16> self.console.print(table)
<17>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.console = Console()
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
+
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
for key, value in self.whatToChoose.items():
self.whatToChoose[key] = self.mh.sortDictionary(value)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>value)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
- # ok so this looks wacky but hear me out here
- # a.update(b)
- # adds all content of dict b onto end of dict a
- # no way to add it to front, so I have to do this :)
+ # Creates and prints the probability table
+ self.produceProbTable(new_dict)
+
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s>
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========changed ref 3===========
# module: ciphey.mathsHelper
class mathsHelper:
def newSort(self, newDict):
# gets the key of the dictionary
# keyDict = list(newDict.keys())[0]
# gets the items of that key (which is a dictionary)
d = dict(newDict)
# (f"d is {d}")
+ logger.debug(f"The old dictionary before newSort() is {newDict}")
sortedI = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
+ logger.debug(f"The dictionary after newSort() is {sortedI}")
# sortedI = sortDictionary(x)
return sortedI
===========changed ref 4===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
for key, value in probTable.items():
+ logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
maxLocal = maxLocal + value2
if maxLocal > maxOverall:
+ logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
# removes the highest key from the prob table
del probTable[highestKey]
# returns the max dict (at the start) with the prob table
+ # this way, it should always work on most likely first.
- # this way, it should always work on most likely first.#
+ logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
db6fc57603bd95f35c3502f9446ab86e65d39daf
|
Rich probability table fully implemented
|
<30>:<add> logger.debug(
<add> f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
<del> logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
<31>:<add> )
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> for key, value in probTable.items():
<13> logger.debug(f"Sorting {key}")
<14> maxLocal = 0
<15> # for each item in that table
<16> for key2, value2 in value.items():
<17> maxLocal = maxLocal + value2
<18> if maxLocal > maxOverall:
<19> logger.debug(f"New max local found {maxLocal}")
<20> # because the dict doesnt reset
<21> maxDictPair = {}
<22> maxOverall = maxLocal
<23> # so eventually, we get the maximum dict pairing?
<24> maxDictPair[key] = value
<25> highestKey = key
<26> # removes the highest key from the prob table
<27> del probTable[highestKey]
<28> # returns the max dict (at the start) with the prob table
<29> # this way, it should always work on most likely first.
<30> logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
<31> d = {**maxDictPair, **probTable}
<32> logger.debug(f"The new sorted prob table is {d}")
<33> return d
<34>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
ciphey.__main__/Ciphey.produceProbTable
|
Modified
|
Ciphey~Ciphey
|
db6fc57603bd95f35c3502f9446ab86e65d39daf
|
Rich probability table fully implemented
|
<19>:<add> val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
<del> val_as_percent = str(round(self.mh.percentage(value, 1), 2))
<21>:<add> if "Base" in keyStr:
<add> keyStr = keyStr[0:-2]
|
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
<0> """Produces the probability table using Rich's API
<1>
<2> :probTable: the probability distribution table returned by the neural network
<3> :returns: Nothing, it prints out the prob table.
<4>
<5> """
<6> table = Table(show_header=True, header_style="bold magenta")
<7> table.add_column("Name of Cipher")
<8> table.add_column("Probability", justify="right")
<9> self.console.print(table)
<10> # for every key, value in dict add a row
<11> # I think key is self.caesarcipher and not "caesar cipher"
<12> # i must callName() somewhere else in this code
<13> for k, v in probTable.items():
<14> for key, value in v.items():
<15> # Prevents the table from showing pointless 0.01 probs as they're faked
<16> if value == 0.01:
<17> continue
<18> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<19> val_as_percent = str(round(self.mh.percentage(value, 1), 2))
<20> keyStr = str(key).capitalize()
<21> logger.debug(
<22> f"The value as percentage is {val_as_percent} and key is {keyStr}"
<23> )
<24> table.add_row(keyStr, val_as_percent)
<25> self.console.print(table)
<26>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.mh = mh.mathsHelper()
self.console = Console()
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
at: mathsHelper.mathsHelper
percentage(part, whole)
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
maxLocal = maxLocal + value2
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
# removes the highest key from the prob table
del probTable[highestKey]
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
+ logger.debug(
+ f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
- logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
+ )
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
db6fc57603bd95f35c3502f9446ab86e65d39daf
|
Rich probability table fully implemented
|
<1>:<add> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<del> description="Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it."
<2>:<add> Examples:
<add> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<add> """
|
# module: ciphey.__main__
def main():
<0> parser = argparse.ArgumentParser(
<1> description="Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it."
<2> )
<3> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<4> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<5> parser.add_argument(
<6> "-g",
<7> "--greppable",
<8> help="Only output the answer, no progress bars or information. Useful for grep",
<9> required=False,
<10> )
<11> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<12> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<13> parser.add_argument(
<14> "-c",
<15> "--printcipher",
<16> help="Do you want information on the cipher used?",
<17> required=False,
<18> )
<19>
<20> parser.add_argument(
<21> "-d", "--debug", help="Activates debug mode", required=False,
<22> )
<23> args = vars(parser.parse_args())
<24> if args["printcipher"] != None:
<25> cipher = True
<26> else:
<27> cipher = False
<28> if args["greppable"] != None:
<29> greppable = True
<30> else:
<31> greppable = False
<32> if args["debug"] != None:
<33> debug = True
<34> else:
<35> debug = False
<36>
<37> if args["text"]:
<38> cipherObj = Ciphey(args["text"], greppable, cipher, debug)
<39> cipherObj.decrypt()
<40> </s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
print("No arguments were supplied. Look at the help menu with -h or --help")
===========unchanged ref 0===========
at: argparse
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: ciphey.__main__
Ciphey(text, grep=False, cipher=False, debug=False)
at: ciphey.__main__.Ciphey
decrypt()
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
"""Produces the probability table using Rich's API
:probTable: the probability distribution table returned by the neural network
:returns: Nothing, it prints out the prob table.
"""
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name of Cipher")
table.add_column("Probability", justify="right")
self.console.print(table)
# for every key, value in dict add a row
# I think key is self.caesarcipher and not "caesar cipher"
# i must callName() somewhere else in this code
for k, v in probTable.items():
for key, value in v.items():
# Prevents the table from showing pointless 0.01 probs as they're faked
if value == 0.01:
continue
logger.debug(f"Key is {str(key)} and value is {str(value)}")
+ val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
- val_as_percent = str(round(self.mh.percentage(value, 1), 2))
keyStr = str(key).capitalize()
+ if "Base" in keyStr:
+ keyStr = keyStr[0:-2]
logger.debug(
f"The value as percentage is {val_as_percent} and key is {keyStr}"
)
table.add_row(keyStr, val_as_percent)
self.console.print(table)
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
maxLocal = maxLocal + value2
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
# removes the highest key from the prob table
del probTable[highestKey]
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
+ logger.debug(
+ f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
- logger.debug(f"The prob table is {probTable} and the maxDictPair is {maxDictPair}")
+ )
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
14a7bb2d561619630e56eabc37ae6fd0e9525432
|
Prob table doesnt print on greppable mode
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<2> self.whatToChoose = {
<3> self.hash: {
<4> "sha1": self.probabilityDistribution[0],
<5> "md5": self.probabilityDistribution[1],
<6> "sha256": self.probabilityDistribution[2],
<7> "sha512": self.probabilityDistribution[3],
<8> },
<9> self.basic: {"caesar": self.probabilityDistribution[4]},
<10> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<11> self.encoding: {
<12> "reverse": self.probabilityDistribution[6],
<13> "base64": self.probabilityDistribution[7],
<14> "binary": self.probabilityDistribution[8],
<15> "hexadecimal": self.probabilityDistribution[9],
<16> "ascii": self.probabilityDistribution[10],
<17> "morse": self.probabilityDistribution[11],
<18> },
<19> }
<20>
<21> logger.debug(
<22> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<23> )
<24>
<25> # sorts each indiviudal sub-dictionary
<26> for key, value in self.whatToChoose.items():
<27> for k, v in value.items():
<28> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<29> if v < 0.01:
<30> self.whatToChoose[key][k] = 0.01
<31> logger.debug(
<32> f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
<33> )
<34>
<35> for key, value in self.whatToChoose.items():
<36> self.whatToChoose[key] = self.</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
at: ciphey.neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
|
ciphey.__main__/Ciphey.produceProbTable
|
Modified
|
Ciphey~Ciphey
|
14a7bb2d561619630e56eabc37ae6fd0e9525432
|
Prob table doesnt print on greppable mode
|
<9>:<del> self.console.print(table)
|
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
<0> """Produces the probability table using Rich's API
<1>
<2> :probTable: the probability distribution table returned by the neural network
<3> :returns: Nothing, it prints out the prob table.
<4>
<5> """
<6> table = Table(show_header=True, header_style="bold magenta")
<7> table.add_column("Name of Cipher")
<8> table.add_column("Probability", justify="right")
<9> self.console.print(table)
<10> # for every key, value in dict add a row
<11> # I think key is self.caesarcipher and not "caesar cipher"
<12> # i must callName() somewhere else in this code
<13> for k, v in probTable.items():
<14> for key, value in v.items():
<15> # Prevents the table from showing pointless 0.01 probs as they're faked
<16> if value == 0.01:
<17> continue
<18> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<19> val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
<20> keyStr = str(key).capitalize()
<21> if "Base" in keyStr:
<22> keyStr = keyStr[0:-2]
<23> logger.debug(
<24> f"The value as percentage is {val_as_percent} and key is {keyStr}"
<25> )
<26> table.add_row(keyStr, val_as_percent)
<27> self.console.print(table)
<28>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.mh = mh.mathsHelper()
self.console = Console()
at: mathsHelper.mathsHelper
percentage(part, whole)
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
for key, value in self.whatToChoose.items():
self.whatToChoose[key] = self.mh.sortDictionary(value)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
+ if not self.greppable:
+ self.produceProbTable(new_dict)
- self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s>f)
for i in range(0, self.level):
# open file and go through each text item
pass
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
d05f7d5f3b0288bdaa280bb8b650774c54683546
|
Fixed request timeout, started on improving the readme
|
<12>:<add> while len(maxDictPair) < len(probTable):
<add> for key, value in probTable.items():
<del> for key, value in probTable.items():
<13>:<add> logger.debug(f"Sorting {key}")
<del> logger.debug(f"Sorting {key}")
<14>:<add>
<add> maxLocal = 0
<del> maxLocal = 0
<15>:<add> # for each item in that table
<del> # for each item in that table
<16>:<add> for key2, value2 in value.items():
<del> for key2, value2 in value.items():
<17>:<add> maxLocal = maxLocal + value2
<del> maxLocal = maxLocal + value2
<18>:<add> if maxLocal > maxOverall:
<del> if maxLocal > maxOverall:
<19>:<add> logger.debug(f"New max local found {maxLocal}")
<del> logger.debug(f"New max local found {maxLocal}")
<20>:<add> # because the dict doesnt reset
<del> # because the dict doesnt reset
<21>:<add> maxDictPair = {}
<del> maxDictPair = {}
<22>:<add> maxOverall = maxLocal
<del> maxOverall = maxLocal
<23>:<add> # so eventually, we get the maximum dict pairing?
<del> # so eventually, we get the maximum dict pairing?
<24>:<add> maxDictPair[key] = value
<del> maxDictPair[key] = value
<25>:<add> highestKey = key
<del> highestKey = key
<26>:<add> # removes the highest key from the prob table
<del> # removes the highest key from the prob table
<27>:<add> del probTable[highest
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> for key, value in probTable.items():
<13> logger.debug(f"Sorting {key}")
<14> maxLocal = 0
<15> # for each item in that table
<16> for key2, value2 in value.items():
<17> maxLocal = maxLocal + value2
<18> if maxLocal > maxOverall:
<19> logger.debug(f"New max local found {maxLocal}")
<20> # because the dict doesnt reset
<21> maxDictPair = {}
<22> maxOverall = maxLocal
<23> # so eventually, we get the maximum dict pairing?
<24> maxDictPair[key] = value
<25> highestKey = key
<26> # removes the highest key from the prob table
<27> del probTable[highestKey]
<28> # returns the max dict (at the start) with the prob table
<29> # this way, it should always work on most likely first.
<30> logger.debug(
<31> f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
<32> )
<33> d = {**maxDictPair, **probTable}
<34> logger.debug(f"The new sorted prob table is {d}")
<35> return d
<36>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
ciphey.Decryptor.Hash.hashBuster/beta
|
Modified
|
Ciphey~Ciphey
|
d05f7d5f3b0288bdaa280bb8b650774c54683546
|
Fixed request timeout, started on improving the readme
|
<0>:<add> try:
<add> response = requests.get(
<del> response = requests.get(
<1>:<add> "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
<del> "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
<2>:<add> ).text
<del> ).text
<3>:<add> except requests.exceptions.ReadTimeout as e:
<add> logger.debug(f"Beta failed timeout {e}")
|
# module: ciphey.Decryptor.Hash.hashBuster
def beta(hashvalue, hashtype):
<0> response = requests.get(
<1> "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
<2> ).text
<3> match = re.search(r'/generate-hash/?text=.*?"', response)
<4> if match:
<5> return match.group(1)
<6> else:
<7> return False
<8>
|
===========unchanged ref 0===========
at: re
search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]]
search(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]]
at: requests.api
get(url: Union[Text, bytes], params: Optional[
Union[
SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType],
Tuple[_ParamsMappingKeyType, _ParamsMappingValueType],
Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]],
Union[Text, bytes],
]
]=..., **kwargs) -> Response
at: requests.exceptions
ReadTimeout(*args, **kwargs)
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
+ while len(maxDictPair) < len(probTable):
+ for key, value in probTable.items():
- for key, value in probTable.items():
+ logger.debug(f"Sorting {key}")
- logger.debug(f"Sorting {key}")
+
+ maxLocal = 0
- maxLocal = 0
+ # for each item in that table
- # for each item in that table
+ for key2, value2 in value.items():
- for key2, value2 in value.items():
+ maxLocal = maxLocal + value2
- maxLocal = maxLocal + value2
+ if maxLocal > maxOverall:
- if maxLocal > maxOverall:
+ logger.debug(f"New max local found {maxLocal}")
- logger.debug(f"New max local found {maxLocal}")
+ # because the dict doesnt reset
- # because the dict doesnt reset
+ maxDictPair = {}
- maxDictPair = {}
+ maxOverall = maxLocal
- maxOverall = maxLocal
+ # so eventually, we get the maximum dict pairing?
- # so eventually, we get the maximum dict pairing?
+ maxDictPair[key] = value
- maxDictPair[key] = value
</s>
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s> dict pairing?
+ maxDictPair[key] = value
- maxDictPair[key] = value
+ highestKey = key
- highestKey = key
+ # removes the highest key from the prob table
- # removes the highest key from the prob table
+ del probTable[highestKey]
- del probTable[highestKey]
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.Decryptor.Hash.hashBuster/gamma
|
Modified
|
Ciphey~Ciphey
|
d05f7d5f3b0288bdaa280bb8b650774c54683546
|
Fixed request timeout, started on improving the readme
|
<0>:<add> try:
<add> response = requests.get(
<del> response = requests.get(
<1>:<add> "https://www.nitrxgen.net/md5db/" + hashvalue, timeout=5
<del> "https://www.nitrxgen.net/md5db/" + hashvalue, timeout=5
<2>:<add> ).text
<del> ).text
<3>:<add> except requests.exceptions.ReadTimeout as e:
<add> logger.debug(f"Gamma failed with {e}")
|
# module: ciphey.Decryptor.Hash.hashBuster
def gamma(hashvalue, hashtype):
<0> response = requests.get(
<1> "https://www.nitrxgen.net/md5db/" + hashvalue, timeout=5
<2> ).text
<3> if response:
<4> return response
<5> else:
<6> return False
<7>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.Hash.hashBuster.beta
match = re.search(r'/generate-hash/?text=.*?"', response)
at: requests.api
get(url: Union[Text, bytes], params: Optional[
Union[
SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType],
Tuple[_ParamsMappingKeyType, _ParamsMappingValueType],
Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]],
Union[Text, bytes],
]
]=..., **kwargs) -> Response
at: typing.Match
pos: int
endpos: int
lastindex: Optional[int]
lastgroup: Optional[AnyStr]
string: AnyStr
re: Pattern[AnyStr]
group(group1: Union[str, int], group2: Union[str, int], /, *groups: Union[str, int]) -> Tuple[AnyStr, ...]
group(group: Union[str, int]=..., /) -> AnyStr
===========changed ref 0===========
# module: ciphey.Decryptor.Hash.hashBuster
def beta(hashvalue, hashtype):
+ try:
+ response = requests.get(
- response = requests.get(
+ "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
- "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
+ ).text
- ).text
+ except requests.exceptions.ReadTimeout as e:
+ logger.debug(f"Beta failed timeout {e}")
match = re.search(r'/generate-hash/?text=.*?"', response)
if match:
return match.group(1)
else:
return False
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
+ while len(maxDictPair) < len(probTable):
+ for key, value in probTable.items():
- for key, value in probTable.items():
+ logger.debug(f"Sorting {key}")
- logger.debug(f"Sorting {key}")
+
+ maxLocal = 0
- maxLocal = 0
+ # for each item in that table
- # for each item in that table
+ for key2, value2 in value.items():
- for key2, value2 in value.items():
+ maxLocal = maxLocal + value2
- maxLocal = maxLocal + value2
+ if maxLocal > maxOverall:
- if maxLocal > maxOverall:
+ logger.debug(f"New max local found {maxLocal}")
- logger.debug(f"New max local found {maxLocal}")
+ # because the dict doesnt reset
- # because the dict doesnt reset
+ maxDictPair = {}
- maxDictPair = {}
+ maxOverall = maxLocal
- maxOverall = maxLocal
+ # so eventually, we get the maximum dict pairing?
- # so eventually, we get the maximum dict pairing?
+ maxDictPair[key] = value
- maxDictPair[key] = value
</s>
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s> dict pairing?
+ maxDictPair[key] = value
- maxDictPair[key] = value
+ highestKey = key
- highestKey = key
+ # removes the highest key from the prob table
- # removes the highest key from the prob table
+ del probTable[highestKey]
- del probTable[highestKey]
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.Decryptor.Hash.hashBuster/theta
|
Modified
|
Ciphey~Ciphey
|
d05f7d5f3b0288bdaa280bb8b650774c54683546
|
Fixed request timeout, started on improving the readme
|
<0>:<add> try:
<add> response = requests.get(
<del> response = requests.get(
<1>:<add> "https://md5decrypt.net/Api/api.php?hash=%s&hash_type=%s&[email protected]&code=1152464b80a61728"
<del> "https://md5decrypt.net/Api/api.php?hash=%s&hash_type=%s&[email protected]&code=1152464b80a61728"
<2>:<add> % (hashvalue, hashtype),
<del> % (hashvalue, hashtype),
<3>:<add> timeout=5,
<del> timeout=5,
<4>:<add> ).text
<del> ).text
<5>:<add> except requests.exceptions.ReadTimeout as e:
<add> logger.debug(f"Gamma failed with {e}")
|
# module: ciphey.Decryptor.Hash.hashBuster
def theta(hashvalue, hashtype):
<0> response = requests.get(
<1> "https://md5decrypt.net/Api/api.php?hash=%s&hash_type=%s&[email protected]&code=1152464b80a61728"
<2> % (hashvalue, hashtype),
<3> timeout=5,
<4> ).text
<5> if len(response) != 0:
<6> return response
<7> else:
<8> return False
<9>
|
===========unchanged ref 0===========
at: requests.api
get(url: Union[Text, bytes], params: Optional[
Union[
SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType],
Tuple[_ParamsMappingKeyType, _ParamsMappingValueType],
Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]],
Union[Text, bytes],
]
]=..., **kwargs) -> Response
===========changed ref 0===========
# module: ciphey.Decryptor.Hash.hashBuster
def gamma(hashvalue, hashtype):
+ try:
+ response = requests.get(
- response = requests.get(
+ "https://www.nitrxgen.net/md5db/" + hashvalue, timeout=5
- "https://www.nitrxgen.net/md5db/" + hashvalue, timeout=5
+ ).text
- ).text
+ except requests.exceptions.ReadTimeout as e:
+ logger.debug(f"Gamma failed with {e}")
if response:
return response
else:
return False
===========changed ref 1===========
# module: ciphey.Decryptor.Hash.hashBuster
def beta(hashvalue, hashtype):
+ try:
+ response = requests.get(
- response = requests.get(
+ "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
- "https://hashtoolkit.com/reverse-hash/?hash=", hashvalue, timeout=5
+ ).text
- ).text
+ except requests.exceptions.ReadTimeout as e:
+ logger.debug(f"Beta failed timeout {e}")
match = re.search(r'/generate-hash/?text=.*?"', response)
if match:
return match.group(1)
else:
return False
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
+ while len(maxDictPair) < len(probTable):
+ for key, value in probTable.items():
- for key, value in probTable.items():
+ logger.debug(f"Sorting {key}")
- logger.debug(f"Sorting {key}")
+
+ maxLocal = 0
- maxLocal = 0
+ # for each item in that table
- # for each item in that table
+ for key2, value2 in value.items():
- for key2, value2 in value.items():
+ maxLocal = maxLocal + value2
- maxLocal = maxLocal + value2
+ if maxLocal > maxOverall:
- if maxLocal > maxOverall:
+ logger.debug(f"New max local found {maxLocal}")
- logger.debug(f"New max local found {maxLocal}")
+ # because the dict doesnt reset
- # because the dict doesnt reset
+ maxDictPair = {}
- maxDictPair = {}
+ maxOverall = maxLocal
- maxOverall = maxLocal
+ # so eventually, we get the maximum dict pairing?
- # so eventually, we get the maximum dict pairing?
+ maxDictPair[key] = value
- maxDictPair[key] = value
</s>
===========changed ref 3===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s> dict pairing?
+ maxDictPair[key] = value
- maxDictPair[key] = value
+ highestKey = key
- highestKey = key
+ # removes the highest key from the prob table
- # removes the highest key from the prob table
+ del probTable[highestKey]
- del probTable[highestKey]
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
aededaab47d40c8fb7a83f446c8553e486db4d73
|
Auto stash before checking out "HEAD"
|
<28>:<add> # removes the highest key from the prob table
<del> # removes the highest key from the prob table
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> while len(maxDictPair) < len(probTable):
<13> for key, value in probTable.items():
<14> logger.debug(f"Sorting {key}")
<15>
<16> maxLocal = 0
<17> # for each item in that table
<18> for key2, value2 in value.items():
<19> maxLocal = maxLocal + value2
<20> if maxLocal > maxOverall:
<21> logger.debug(f"New max local found {maxLocal}")
<22> # because the dict doesnt reset
<23> maxDictPair = {}
<24> maxOverall = maxLocal
<25> # so eventually, we get the maximum dict pairing?
<26> maxDictPair[key] = value
<27> highestKey = key
<28> # removes the highest key from the prob table
<29> del probTable[highestKey]
<30> # returns the max dict (at the start) with the prob table
<31> # this way, it should always work on most likely first.
<32> logger.debug(
<33> f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
<34> )
<35> d = {**maxDictPair, **probTable}
<36> logger.debug(f"The new sorted prob table is {d}")
<37> return d
<38>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
items() -> _OrderedDictItemsView[_KT, _VT]
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.check1000Words
|
Modified
|
Ciphey~Ciphey
|
aededaab47d40c8fb7a83f446c8553e486db4d73
|
Auto stash before checking out "HEAD"
|
<2>:<add> logger.debug(f"Check 1000 words text is {text}")
<5>:<add> logger.debug(f"Word in check1000 is {word}")
<7>:<add> if word.lower() == text.lower():
<add> logger.debug(f"THEY're the SAME! {word} and {text}")
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def check1000Words(self, text):
<0> check = dict.fromkeys(self.top1000Words)
<1> text = self.cleanText(text)
<2> # If any of the top 1000 words in the text appear
<3> # return true
<4> for word in text:
<5> # I was debating using any() here, but I think they're the
<6> # same speed so it doesn't really matter too much
<7> if word in check:
<8> logger.debug(f"Check 1000 words returns True for word {word}")
<9> return True
<10> else:
<11> return False
<12>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
cleanText(text)
===========unchanged ref 1===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.__init__
self.top1000Words = {'able': None, 'about': None, 'above': None, 'act': None, 'add': None, 'afraid': None, 'after': None, 'again': None, 'against': None, 'age': None, 'ago': None, 'agree': None, 'air': None, 'all': None, 'allow': None, 'also': None, 'always': None, 'am': None, 'among': None, 'an': None, 'and': None, 'anger': None, 'animal': None, 'answer': None, 'any': None, 'appear': None, 'apple': None, 'are': None, 'area': None, 'arm': None, 'arrange': None, 'arrive': None, 'art': None, 'as': None, 'ask': None, 'at': None, 'atom': None, 'baby': None, 'back': None, 'bad': None, 'ball': None, 'band': None, 'bank': None, 'bar': None, 'base': None, 'basic': None, 'bat': None, 'be': None, 'bear': None, 'beat': None, 'beauty': None, 'bed': None, 'been': None, 'before': None, 'began': None, 'begin': None, 'behind': None, 'believe': None, 'bell': None, 'best': None, 'better': None, 'between': None, 'big': None, 'bird': None, 'bit': None, 'black': None, 'block': None, 'blood': None, 'blow': None, 'blue': None, 'board': None, 'boat': None, 'body': None, 'bone': None, 'book': None, 'born': None, 'both': None, 'bottom': None, 'bought': None, 'box': None, 'boy': None, 'branch': None, 'bread': None, 'break': None, 'bright': None, 'bring': None, 'broad': None, 'broke': None, 'brother': None, 'brought': None, 'b</s>
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
while len(maxDictPair) < len(probTable):
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
maxLocal = maxLocal + value2
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
+ # removes the highest key from the prob table
- # removes the highest key from the prob table
del probTable[highestKey]
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
060c547d1d7509ccf19e59dc13cca01da5e20c8b
|
Fixing sorting bug
|
<12>:<add> counterMax = 0
<add> counterProb = len(probTable)
<add> while counterMax < counterProb:
<del> while len(maxDictPair) < len(probTable):
<30>:<add> counterMax += 1
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> while len(maxDictPair) < len(probTable):
<13> for key, value in probTable.items():
<14> logger.debug(f"Sorting {key}")
<15>
<16> maxLocal = 0
<17> # for each item in that table
<18> for key2, value2 in value.items():
<19> maxLocal = maxLocal + value2
<20> if maxLocal > maxOverall:
<21> logger.debug(f"New max local found {maxLocal}")
<22> # because the dict doesnt reset
<23> maxDictPair = {}
<24> maxOverall = maxLocal
<25> # so eventually, we get the maximum dict pairing?
<26> maxDictPair[key] = value
<27> highestKey = key
<28> # removes the highest key from the prob table
<29> del probTable[highestKey]
<30> # returns the max dict (at the start) with the prob table
<31> # this way, it should always work on most likely first.
<32> logger.debug(
<33> f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
<34> )
<35> d = {**maxDictPair, **probTable}
<36> logger.debug(f"The new sorted prob table is {d}")
<37> return d
<38>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
items() -> _OrderedDictItemsView[_KT, _VT]
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
09e9ed44589282443ed92db31d81ed8893bfd020
|
Done for the night
|
<14>:<add> while counterMax < counterProb:
<del> while counterMax < counterProb:
<17>:<del>
<22>:<add> if maxLocal > maxOverall:
<del> if maxLocal > maxOverall:
<23>:<add> logger.debug(f"New max local found {maxLocal}")
<del> logger.debug(f"New max local found {maxLocal}")
<24>:<add> # because the dict doesnt reset
<del> # because the dict doesnt reset
<25>:<add> maxDictPair = {}
<del> maxDictPair = {}
<26>:<add> maxOverall = maxLocal
<del> maxOverall = maxLocal
<27>:<add> # so eventually, we get the maximum dict pairing?
<del> # so eventually, we get the maximum dict pairing?
<28>:<add> maxDictPair[key] = value
<del> maxDictPair[key] = value
<29>:<add> highestKey = key
<del> highestKey = key
<31>:<add> logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
<add> logger.debug(f"Removing {probTable[highestKey]}")
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> counterMax = 0
<13> counterProb = len(probTable)
<14> while counterMax < counterProb:
<15> for key, value in probTable.items():
<16> logger.debug(f"Sorting {key}")
<17>
<18> maxLocal = 0
<19> # for each item in that table
<20> for key2, value2 in value.items():
<21> maxLocal = maxLocal + value2
<22> if maxLocal > maxOverall:
<23> logger.debug(f"New max local found {maxLocal}")
<24> # because the dict doesnt reset
<25> maxDictPair = {}
<26> maxOverall = maxLocal
<27> # so eventually, we get the maximum dict pairing?
<28> maxDictPair[key] = value
<29> highestKey = key
<30> # removes the highest key from the prob table
<31> del probTable[highestKey]
<32> counterMax += 1
<33> # returns the max dict (at the start) with the prob table
<34> # this way, it should always work on most likely first.
<35> logger.debug(
<36> f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
<37> )
<38> d = {**maxDictPair, **probTable}
<39> logger.debug(f</s>
|
===========below chunk 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
return d
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
items() -> _OrderedDictItemsView[_KT, _VT]
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
bf2e40518ea4ea7e77ac6bfd692f0d97c1813ba2
|
It runs but it doesn't work
|
<15>:<add> maxOverall = 0
<add> highestKey = None
<add> logger.debug(
<add> f"Running while loop in sortProbTable, counterMax is {counterMax}"
<add> )
<20>:<add> logger.debug(
<add> f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
<add> )
<21>:<add> logger.debug(
<add> f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
<add> )
<29>:<add> logger.debug(f"Highest key is {highestKey}")
<33>:<add> logger.debug(f"Prob table after deletion is {probTable}")
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> counterMax = 0
<13> counterProb = len(probTable)
<14> while counterMax < counterProb:
<15> for key, value in probTable.items():
<16> logger.debug(f"Sorting {key}")
<17> maxLocal = 0
<18> # for each item in that table
<19> for key2, value2 in value.items():
<20> maxLocal = maxLocal + value2
<21> if maxLocal > maxOverall:
<22> logger.debug(f"New max local found {maxLocal}")
<23> # because the dict doesnt reset
<24> maxDictPair = {}
<25> maxOverall = maxLocal
<26> # so eventually, we get the maximum dict pairing?
<27> maxDictPair[key] = value
<28> highestKey = key
<29> # removes the highest key from the prob table
<30> logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
<31> logger.debug(f"Removing {probTable[highestKey]}")
<32> del probTable[highestKey]
<33> counterMax += 1
<34> # returns the max dict (at the start) with the prob table
<35> # this way, it should always work on most likely first.
<36> logger.debug(
<37> f"The prob table is {prob</s>
|
===========below chunk 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
)
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
46c238aa394bdbd0b7a31047ffd71fff673fd82d
|
Probability table is fixed
|
<5>:<add> emptyDict = {}
<del>
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5>
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> counterMax = 0
<13> counterProb = len(probTable)
<14> while counterMax < counterProb:
<15> maxOverall = 0
<16> highestKey = None
<17> logger.debug(
<18> f"Running while loop in sortProbTable, counterMax is {counterMax}"
<19> )
<20> for key, value in probTable.items():
<21> logger.debug(f"Sorting {key}")
<22> maxLocal = 0
<23> # for each item in that table
<24> for key2, value2 in value.items():
<25> logger.debug(
<26> f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
<27> )
<28> maxLocal = maxLocal + value2
<29> logger.debug(
<30> f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
<31> )
<32> if maxLocal > maxOverall:
<33> logger.debug(f"New max local found {maxLocal}")
<34> # because the dict doesnt reset
<35> maxDictPair = {}
<36> maxOverall = maxLocal
<37> # so eventually, we get the maximum dict pairing?
<38> maxDictPair[key] = value
<39> highestKey = key
<40> logger.debug(</s>
|
===========below chunk 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
d = {**maxDictPair, **probTable}
logger.debug(f"The new sorted prob table is {d}")
return d
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
4cb06b387a7d8b492dd3b7979ed3808d5ae70224
|
Added more decryption help
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<2> self.whatToChoose = {
<3> self.hash: {
<4> "sha1": self.probabilityDistribution[0],
<5> "md5": self.probabilityDistribution[1],
<6> "sha256": self.probabilityDistribution[2],
<7> "sha512": self.probabilityDistribution[3],
<8> },
<9> self.basic: {"caesar": self.probabilityDistribution[4]},
<10> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<11> self.encoding: {
<12> "reverse": self.probabilityDistribution[6],
<13> "base64": self.probabilityDistribution[7],
<14> "binary": self.probabilityDistribution[8],
<15> "hexadecimal": self.probabilityDistribution[9],
<16> "ascii": self.probabilityDistribution[10],
<17> "morse": self.probabilityDistribution[11],
<18> },
<19> }
<20>
<21> logger.debug(
<22> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<23> )
<24>
<25> # sorts each indiviudal sub-dictionary
<26> for key, value in self.whatToChoose.items():
<27> for k, v in value.items():
<28> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<29> if v < 0.01:
<30> self.whatToChoose[key][k] = 0.01
<31> logger.debug(
<32> f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
<33> )
<34>
<35> for key, value in self.whatToChoose.items():
<36> self.whatToChoose[key] = self.</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
if not self.greppable:
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
at: ciphey.neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
|
|
ciphey.__main__/Ciphey.decryptNormal
|
Modified
|
Ciphey~Ciphey
|
4cb06b387a7d8b492dd3b7979ed3808d5ae70224
|
Added more decryption help
|
<20>:<add> print("The cipher used is " + ret["Cipher"] + ".")
<del> print(ret["Cipher"])
<26>:<add> print("""No encryption found. Here are some tips to help crack the cipher:
<add> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
<add> * If the probability table says 'Caesar Cipher' then it is a normal encryption that Ciphey cannot decrypt yet.
<add> * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, and then HashCat to crack the hash.
<add> * The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log file of all attempted decryptions and manually search it.""")
<del> print("No encryption found. Here's the probabilities we calculated")
|
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
<0> for key, val in self.whatToChoose.items():
<1> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
<2> if not isinstance(key, str):
<3> key.setProbTable(val)
<4> ret = key.decrypt(self.text)
<5> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<6> logger.debug(
<7> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<8> )
<9>
<10> if ret["IsPlaintext?"]:
<11> print(ret["Plaintext"])
<12> if self.cipher:
<13> if ret["Extra Information"] != None:
<14> print(
<15> "The cipher used is",
<16> ret["Cipher"] + ".",
<17> ret["Extra Information"] + ".",
<18> )
<19> else:
<20> print(ret["Cipher"])
<21> return ret
<22>
<23> if not self.greppable:
<24> bar()
<25> logger.debug("No encryption found")
<26> print("No encryption found. Here's the probabilities we calculated")
<27>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.text = text
self.greppable = grep
self.cipher = cipher
at: ciphey.__main__.Ciphey.decrypt
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
self.whatToChoose = new_dict
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
for key, value in self.whatToChoose.items():
self.whatToChoose[key] = self.mh.sortDictionary(value)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
+ # TODO is this code redundant because of self.mh.sortProbTable?
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
if not self.greppable:
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s>ryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
|
ciphey.__main__/Ciphey.decryptNormal
|
Modified
|
Ciphey~Ciphey
|
08987c3dce33f28cd8d1fa65866f8219c6def306
|
Updated readme
|
<26>:<add> print(
<add> """No encryption found. Here are some tips to help crack the cipher:
<del> print("""No encryption found. Here are some tips to help crack the cipher:
<30>:<add> * The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log file of all attempted decryptions and manually search it."""
<del> * The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a
|
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
<0> for key, val in self.whatToChoose.items():
<1> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
<2> if not isinstance(key, str):
<3> key.setProbTable(val)
<4> ret = key.decrypt(self.text)
<5> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<6> logger.debug(
<7> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<8> )
<9>
<10> if ret["IsPlaintext?"]:
<11> print(ret["Plaintext"])
<12> if self.cipher:
<13> if ret["Extra Information"] != None:
<14> print(
<15> "The cipher used is",
<16> ret["Cipher"] + ".",
<17> ret["Extra Information"] + ".",
<18> )
<19> else:
<20> print("The cipher used is " + ret["Cipher"] + ".")
<21> return ret
<22>
<23> if not self.greppable:
<24> bar()
<25> logger.debug("No encryption found")
<26> print("""No encryption found. Here are some tips to help crack the cipher:
<27> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
<28> * If the probability table says 'Caesar Cipher' then it is a normal encryption that Ciphey cannot decrypt yet.
<29> * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, and then HashCat to crack the hash.
<30> * The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
# offset: 1
===========unchanged ref 0===========
at: Decryptor.Encoding.encodingParent.EncodingParent
setProbTable(table)
at: Decryptor.Hash.hashParent.HashParent
decrypt(text)
setProbTable(val)
at: Decryptor.basicEncryption.basic_parent.BasicParent
decrypt(text)
at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent
decrypt(text)
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent
setProbTable(prob)
at: ciphey.__main__.Ciphey.__init__
self.text = text
self.greppable = grep
self.cipher = cipher
at: ciphey.__main__.Ciphey.decrypt
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
self.whatToChoose = new_dict
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
===========unchanged ref 1===========
__marker = object()
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.check1000Words
|
Modified
|
Ciphey~Ciphey
|
0ed017996576f73c2d3a3a78fe8d564dfdbcb193
|
Updates
|
<1>:<add> logger.debug(f"text before cleaning is {text}")
<9>:<del> if word.lower() == text.lower():
<10>:<del> logger.debug(f"THEY're the SAME! {word} and {text}")
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def check1000Words(self, text):
<0> check = dict.fromkeys(self.top1000Words)
<1> text = self.cleanText(text)
<2> logger.debug(f"Check 1000 words text is {text}")
<3> # If any of the top 1000 words in the text appear
<4> # return true
<5> for word in text:
<6> logger.debug(f"Word in check1000 is {word}")
<7> # I was debating using any() here, but I think they're the
<8> # same speed so it doesn't really matter too much
<9> if word.lower() == text.lower():
<10> logger.debug(f"THEY're the SAME! {word} and {text}")
<11> if word in check:
<12> logger.debug(f"Check 1000 words returns True for word {word}")
<13> return True
<14> else:
<15> return False
<16>
| |
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
0ed017996576f73c2d3a3a78fe8d564dfdbcb193
|
Updates
|
<12>:<add> action='store_true',
<20>:<add> action='store_true',
<24>:<add> "-d", "--debug", help="Activates debug mode", action='store_true', required=False,
<del> "-d", "--debug", help="Activates debug mode", required=False,
|
# module: ciphey.__main__
def main():
<0> parser = argparse.ArgumentParser(
<1> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<2> Examples:
<3> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<4> """
<5> )
<6> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<7> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<8> parser.add_argument(
<9> "-g",
<10> "--greppable",
<11> help="Only output the answer, no progress bars or information. Useful for grep",
<12> required=False,
<13> )
<14> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<15> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<16> parser.add_argument(
<17> "-c",
<18> "--printcipher",
<19> help="Do you want information on the cipher used?",
<20> required=False,
<21> )
<22>
<23> parser.add_argument(
<24> "-d", "--debug", help="Activates debug mode", required=False,
<25> )
<26> args = vars(parser.parse_args())
<27> if args["printcipher"] != None:
<28> cipher = True
<29> else:
<30> cipher = False
<31> if args["greppable"] != None:
<32> greppable = True
<33> else:
<34> greppable = False
<35> if args["debug"] != None:
<36> debug = True
<37> else:
<38> debug = False
<39>
</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
cipherObj = Ciphey(args["text"], greppable, cipher, debug)
cipherObj.decrypt()
else:
print("No arguments were supplied. Look at the help menu with -h or --help")
===========unchanged ref 0===========
at: argparse
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: ciphey.__main__
Ciphey(text, grep=False, cipher=False, debug=False)
at: ciphey.__main__.Ciphey
decrypt()
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def check1000Words(self, text):
check = dict.fromkeys(self.top1000Words)
+ logger.debug(f"text before cleaning is {text}")
text = self.cleanText(text)
logger.debug(f"Check 1000 words text is {text}")
# If any of the top 1000 words in the text appear
# return true
for word in text:
logger.debug(f"Word in check1000 is {word}")
# I was debating using any() here, but I think they're the
# same speed so it doesn't really matter too much
- if word.lower() == text.lower():
- logger.debug(f"THEY're the SAME! {word} and {text}")
if word in check:
logger.debug(f"Check 1000 words returns True for word {word}")
return True
else:
return False
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.check1000Words
|
Modified
|
Ciphey~Ciphey
|
79d9e8c05ad7ab51dd095c6fee8f293905c3690e
|
Dictionary checker no longer works on None type texts
|
<0>:<add> if text == None:
<add> return False
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def check1000Words(self, text):
<0> check = dict.fromkeys(self.top1000Words)
<1> logger.debug(f"text before cleaning is {text}")
<2> text = self.cleanText(text)
<3> logger.debug(f"Check 1000 words text is {text}")
<4> # If any of the top 1000 words in the text appear
<5> # return true
<6> for word in text:
<7> logger.debug(f"Word in check1000 is {word}")
<8> # I was debating using any() here, but I think they're the
<9> # same speed so it doesn't really matter too much
<10> if word in check:
<11> logger.debug(f"Check 1000 words returns True for word {word}")
<12> return True
<13> else:
<14> return False
<15>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
cleanText(text)
===========unchanged ref 1===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.__init__
self.top1000Words = {
"able": None,
"about": None,
"above": None,
"act": None,
"add": None,
"afraid": None,
"after": None,
"again": None,
"against": None,
"age": None,
"ago": None,
"agree": None,
"air": None,
"all": None,
"allow": None,
"also": None,
"always": None,
"am": None,
"among": None,
"an": None,
"and": None,
"anger": None,
"animal": None,
"answer": None,
"any": None,
"appear": None,
"apple": None,
"are": None,
"area": None,
"arm": None,
"arrange": None,
"arrive": None,
"art": None,
"as": None,
"ask": None,
"at": None,
"atom": None,
"baby": None,
"back": None,
"bad": None,
"ball": None,
"band": None,
"bank": None,
"bar": None,
"base": None,
"basic": None,
"bat": None,
"be": None,
"bear": None,
"beat": None,
"beauty": None,
"bed": None,
"been": None,
"before": None,
"began": None,
"begin": None,
"behind": None,
"believe": None,
</s>
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
6767b63c1ae8c2bb1ff9a86dfc9b1d80519fb4ec
|
Fixing languagechecker
|
<14>:<add> while counterMax <= counterProb:
<del> while counterMax < counterProb:
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5> emptyDict = {}
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> counterMax = 0
<13> counterProb = len(probTable)
<14> while counterMax < counterProb:
<15> maxOverall = 0
<16> highestKey = None
<17> logger.debug(
<18> f"Running while loop in sortProbTable, counterMax is {counterMax}"
<19> )
<20> for key, value in probTable.items():
<21> logger.debug(f"Sorting {key}")
<22> maxLocal = 0
<23> # for each item in that table
<24> for key2, value2 in value.items():
<25> logger.debug(
<26> f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
<27> )
<28> maxLocal = maxLocal + value2
<29> logger.debug(
<30> f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
<31> )
<32> if maxLocal > maxOverall:
<33> logger.debug(f"New max local found {maxLocal}")
<34> # because the dict doesnt reset
<35> maxDictPair = {}
<36> maxOverall = maxLocal
<37> # so eventually, we get the maximum dict pairing?
<38> maxDictPair[key] = value
<39> highestKey = key
<40> </s>
|
===========below chunk 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
emptyDict = {**emptyDict, **maxDictPair}
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
logger.debug(f"The new sorted prob table is {emptyDict}")
return emptyDict
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
items() -> _OrderedDictItemsView[_KT, _VT]
|
ciphey.Decryptor.Encoding.base64/Base64.goodRet
|
Modified
|
Ciphey~Ciphey
|
6767b63c1ae8c2bb1ff9a86dfc9b1d80519fb4ec
|
Fixing languagechecker
|
<0>:<add> logger.debug(f"Result for base is true, where result is {result}")
|
# module: ciphey.Decryptor.Encoding.base64
class Base64:
def goodRet(self, result, cipher):
<0> return {
<1> "lc": self.lc,
<2> "IsPlaintext?": True,
<3> "Plaintext": result,
<4> "Cipher": cipher,
<5> "Extra Information": None,
<6> }
<7>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.Encoding.base64.Base64.__init__
self.lc = lc
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
emptyDict = {}
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
counterMax = 0
counterProb = len(probTable)
+ while counterMax <= counterProb:
- while counterMax < counterProb:
maxOverall = 0
highestKey = None
logger.debug(
f"Running while loop in sortProbTable, counterMax is {counterMax}"
)
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
logger.debug(
f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
)
maxLocal = maxLocal + value2
logger.debug(
f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
)
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table</s>
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s>
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
emptyDict = {**emptyDict, **maxDictPair}
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
logger.debug(f"The new sorted prob table is {emptyDict}")
return emptyDict
|
ciphey.languageCheckerMod.chisquared/chiSquared.checkChi
|
Modified
|
Ciphey~Ciphey
|
6767b63c1ae8c2bb1ff9a86dfc9b1d80519fb4ec
|
Fixing languagechecker
|
<0>:<add> if text == None:
<add> return False
|
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
<0> """Checks to see if the Chi score is good
<1> if it is, it returns True
<2> Call this when you want to determine whether something is likely to be Chi or not
<3>
<4> Arguments:
<5> * text - the text you want to run a Chi Squared score on
<6>
<7> Outputs:
<8> * True - if it has a significantly lower chi squared score
<9> * False - if it doesn't have a significantly lower chi squared score
<10> """
<11> # runs after every chi squared to see if it's 1 significantly lower than averae
<12> # the or statement is bc if the program has just started I don't want it to ignore the
<13> # ones at the start
<14> self.chiSquared(text)
<15> # If the latest chi squared is less than the standard deviation
<16> # or if not many chi squares have been calculated
<17> # or if every single letter in a text appears exactly once (pangram)
<18> stdSignif = float(
<19> self.average
<20> - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
<21> )
<22> tempy = abs(
<23> self.average
<24> - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
<25> )
<26> if (
<27> self.chisAsaList[-1] <= abs(stdSignif)
<28> or self.totalDone < self.totalDoneThreshold
<29> or self.totalEqual
<30> # or float(self.chisAsaList[-1]) < stdSignif + 0.1
<31> # or float(self.chisAsaList[-1]) > stdSignif - 0.1
<32> ):
<33> logger.debug(f"Chi squared returns true for {text}")
<34> return True
<35> else:
<36> </s>
|
===========below chunk 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
# offset: 1
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.chisquared.chiSquared
chiSquared(text)
at: ciphey.languageCheckerMod.chisquared.chiSquared.__add__
addedObject = chiSquared()
at: ciphey.languageCheckerMod.chisquared.chiSquared.__init__
self.average = 0.0
self.totalDone = 0.0
self.totalEqual = False
self.chisAsaList = []
self.chiSquaredSignificaneThreshold = 1 # how many stds you want to go below it
self.totalDoneThreshold = 10
self.oldstandarddeviation = 0.00
at: ciphey.languageCheckerMod.chisquared.chiSquared.chiSquared
self.totalEqual = self.mh.checkEqual(list(letterFreq.values()))
self.totalDone += 1
self.average = (self.totalChi + maxChiSquare) / self.totalDone
self.oldstandarddeviation = abs(self.standarddeviation)
===========changed ref 0===========
# module: ciphey.Decryptor.Encoding.base64
class Base64:
def goodRet(self, result, cipher):
+ logger.debug(f"Result for base is true, where result is {result}")
return {
"lc": self.lc,
"IsPlaintext?": True,
"Plaintext": result,
"Cipher": cipher,
"Extra Information": None,
}
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
emptyDict = {}
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
counterMax = 0
counterProb = len(probTable)
+ while counterMax <= counterProb:
- while counterMax < counterProb:
maxOverall = 0
highestKey = None
logger.debug(
f"Running while loop in sortProbTable, counterMax is {counterMax}"
)
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
logger.debug(
f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
)
maxLocal = maxLocal + value2
logger.debug(
f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
)
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table</s>
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s>
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
emptyDict = {**emptyDict, **maxDictPair}
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
logger.debug(f"The new sorted prob table is {emptyDict}")
return emptyDict
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
6767b63c1ae8c2bb1ff9a86dfc9b1d80519fb4ec
|
Fixing languagechecker
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<2> self.whatToChoose = {
<3> self.hash: {
<4> "sha1": self.probabilityDistribution[0],
<5> "md5": self.probabilityDistribution[1],
<6> "sha256": self.probabilityDistribution[2],
<7> "sha512": self.probabilityDistribution[3],
<8> },
<9> self.basic: {"caesar": self.probabilityDistribution[4]},
<10> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<11> self.encoding: {
<12> "reverse": self.probabilityDistribution[6],
<13> "base64": self.probabilityDistribution[7],
<14> "binary": self.probabilityDistribution[8],
<15> "hexadecimal": self.probabilityDistribution[9],
<16> "ascii": self.probabilityDistribution[10],
<17> "morse": self.probabilityDistribution[11],
<18> },
<19> }
<20>
<21> logger.debug(
<22> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<23> )
<24>
<25> # sorts each indiviudal sub-dictionary
<26> for key, value in self.whatToChoose.items():
<27> for k, v in value.items():
<28> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<29> if v < 0.01:
<30> self.whatToChoose[key][k] = 0.01
<31> logger.debug(
<32> f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
<33> )
<34>
<35> for key, value in self.whatToChoose.items():
<36> self.whatToChoose[key] = self.</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
# TODO is this code redundant because of self.mh.sortProbTable?
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
if not self.greppable:
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
</s>
===========below chunk 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s>)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
at: ciphey.neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
===========changed ref 0===========
# module: ciphey.Decryptor.Encoding.base64
class Base64:
def goodRet(self, result, cipher):
+ logger.debug(f"Result for base is true, where result is {result}")
return {
"lc": self.lc,
"IsPlaintext?": True,
"Plaintext": result,
"Cipher": cipher,
"Extra Information": None,
}
===========changed ref 1===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
+ if text == None:
+ return False
"""Checks to see if the Chi score is good
if it is, it returns True
Call this when you want to determine whether something is likely to be Chi or not
Arguments:
* text - the text you want to run a Chi Squared score on
Outputs:
* True - if it has a significantly lower chi squared score
* False - if it doesn't have a significantly lower chi squared score
"""
# runs after every chi squared to see if it's 1 significantly lower than averae
# the or statement is bc if the program has just started I don't want it to ignore the
# ones at the start
self.chiSquared(text)
# If the latest chi squared is less than the standard deviation
# or if not many chi squares have been calculated
# or if every single letter in a text appears exactly once (pangram)
stdSignif = float(
self.average
- (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
)
tempy = abs(
self.average
- (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
)
if (
self.chisAsaList[-1] <= abs(stdSignif)
or self.totalDone < self.totalDoneThreshold
or self.totalEqual
# or float(self.chisAsaList[-1]) < stdSignif + 0.1
# or float(self.chisAsaList[-1]) > stdSignif - 0.1
):
logger.debug(f"Chi squared returns true for {text}")
return True
else:
return False
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
emptyDict = {}
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
counterMax = 0
counterProb = len(probTable)
+ while counterMax <= counterProb:
- while counterMax < counterProb:
maxOverall = 0
highestKey = None
logger.debug(
f"Running while loop in sortProbTable, counterMax is {counterMax}"
)
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
logger.debug(
f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
)
maxLocal = maxLocal + value2
logger.debug(
f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
)
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table</s>
|
|
ciphey.__main__/Ciphey.produceProbTable
|
Modified
|
Ciphey~Ciphey
|
6767b63c1ae8c2bb1ff9a86dfc9b1d80519fb4ec
|
Fixing languagechecker
|
<6>:<add> logger.debug(f"Producing log table")
|
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
<0> """Produces the probability table using Rich's API
<1>
<2> :probTable: the probability distribution table returned by the neural network
<3> :returns: Nothing, it prints out the prob table.
<4>
<5> """
<6> table = Table(show_header=True, header_style="bold magenta")
<7> table.add_column("Name of Cipher")
<8> table.add_column("Probability", justify="right")
<9> # for every key, value in dict add a row
<10> # I think key is self.caesarcipher and not "caesar cipher"
<11> # i must callName() somewhere else in this code
<12> for k, v in probTable.items():
<13> for key, value in v.items():
<14> # Prevents the table from showing pointless 0.01 probs as they're faked
<15> if value == 0.01:
<16> continue
<17> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<18> val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
<19> keyStr = str(key).capitalize()
<20> if "Base" in keyStr:
<21> keyStr = keyStr[0:-2]
<22> logger.debug(
<23> f"The value as percentage is {val_as_percent} and key is {keyStr}"
<24> )
<25> table.add_row(keyStr, val_as_percent)
<26> self.console.print(table)
<27>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.mh = mh.mathsHelper()
self.console = Console()
at: ciphey.mathsHelper.mathsHelper
percentage(part, whole)
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
for key, value in self.whatToChoose.items():
self.whatToChoose[key] = self.mh.sortDictionary(value)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
# TODO is this code redundant because of self.mh.sortProbTable?
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
+ if self.greppable == False:
- if not self.greppable:
+ logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s> print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========changed ref 3===========
# module: ciphey.Decryptor.Encoding.base64
class Base64:
def goodRet(self, result, cipher):
+ logger.debug(f"Result for base is true, where result is {result}")
return {
"lc": self.lc,
"IsPlaintext?": True,
"Plaintext": result,
"Cipher": cipher,
"Extra Information": None,
}
===========changed ref 4===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
+ if text == None:
+ return False
"""Checks to see if the Chi score is good
if it is, it returns True
Call this when you want to determine whether something is likely to be Chi or not
Arguments:
* text - the text you want to run a Chi Squared score on
Outputs:
* True - if it has a significantly lower chi squared score
* False - if it doesn't have a significantly lower chi squared score
"""
# runs after every chi squared to see if it's 1 significantly lower than averae
# the or statement is bc if the program has just started I don't want it to ignore the
# ones at the start
self.chiSquared(text)
# If the latest chi squared is less than the standard deviation
# or if not many chi squares have been calculated
# or if every single letter in a text appears exactly once (pangram)
stdSignif = float(
self.average
- (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
)
tempy = abs(
self.average
- (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
)
if (
self.chisAsaList[-1] <= abs(stdSignif)
or self.totalDone < self.totalDoneThreshold
or self.totalEqual
# or float(self.chisAsaList[-1]) < stdSignif + 0.1
# or float(self.chisAsaList[-1]) > stdSignif - 0.1
):
logger.debug(f"Chi squared returns true for {text}")
return True
else:
return False
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
6767b63c1ae8c2bb1ff9a86dfc9b1d80519fb4ec
|
Fixing languagechecker
|
<12>:<add>
<del> action='store_true',
<21>:<add>
<del> action='store_true',
<26>:<add> "-d",
<add> "--debug",
<add> help="Activates debug mode",
<add>
<add> required=False,
<del> "-d", "--debug", help="Activates debug mode", action='store_true', required=False,
|
# module: ciphey.__main__
def main():
<0> parser = argparse.ArgumentParser(
<1> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<2> Examples:
<3> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<4> """
<5> )
<6> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<7> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<8> parser.add_argument(
<9> "-g",
<10> "--greppable",
<11> help="Only output the answer, no progress bars or information. Useful for grep",
<12> action='store_true',
<13> required=False,
<14> )
<15> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<16> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<17> parser.add_argument(
<18> "-c",
<19> "--printcipher",
<20> help="Do you want information on the cipher used?",
<21> action='store_true',
<22> required=False,
<23> )
<24>
<25> parser.add_argument(
<26> "-d", "--debug", help="Activates debug mode", action='store_true', required=False,
<27> )
<28> args = vars(parser.parse_args())
<29> if args["printcipher"] != None:
<30> cipher = True
<31> else:
<32> cipher = False
<33> if args["greppable"] != None:
<34> greppable = True
<35> else:
<36> greppable = False
<37> if args["debug"] !=</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
debug = True
else:
debug = False
if args["text"]:
cipherObj = Ciphey(args["text"], greppable, cipher, debug)
cipherObj.decrypt()
else:
print("No arguments were supplied. Look at the help menu with -h or --help")
===========unchanged ref 0===========
at: argparse
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: ciphey.__main__
Ciphey(text, grep=False, cipher=False, debug=False)
at: ciphey.__main__.Ciphey
decrypt(self)
decrypt()
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
for key, value in self.whatToChoose.items():
self.whatToChoose[key] = self.mh.sortDictionary(value)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
# TODO is this code redundant because of self.mh.sortProbTable?
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
+ if self.greppable == False:
- if not self.greppable:
+ logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s> print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
|
ciphey.mathsHelper/mathsHelper.sortProbTable
|
Modified
|
Ciphey~Ciphey
|
00ff24b1cc764c333dc016afe27ba3cbf3eda345
|
Prob table is now fully sorted
|
<14>:<add> while counterMax < counterProb:
<del> while counterMax <= counterProb:
|
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
<0> """Sorts the probabiltiy table"""
<1> # for each object: prob table in dictionary
<2> maxOverall = 0
<3> maxDictPair = {}
<4> highestKey = None
<5> emptyDict = {}
<6> # sorts the prob table before we find max, and converts it to order dicts
<7> for key, value in probTable.items():
<8> probTable[key] = self.newSort(value)
<9> probTable[key] = dict(probTable[key])
<10>
<11> # gets maximum key then sets it to the front
<12> counterMax = 0
<13> counterProb = len(probTable)
<14> while counterMax <= counterProb:
<15> maxOverall = 0
<16> highestKey = None
<17> logger.debug(
<18> f"Running while loop in sortProbTable, counterMax is {counterMax}"
<19> )
<20> for key, value in probTable.items():
<21> logger.debug(f"Sorting {key}")
<22> maxLocal = 0
<23> # for each item in that table
<24> for key2, value2 in value.items():
<25> logger.debug(
<26> f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
<27> )
<28> maxLocal = maxLocal + value2
<29> logger.debug(
<30> f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
<31> )
<32> if maxLocal > maxOverall:
<33> logger.debug(f"New max local found {maxLocal}")
<34> # because the dict doesnt reset
<35> maxDictPair = {}
<36> maxOverall = maxLocal
<37> # so eventually, we get the maximum dict pairing?
<38> maxDictPair[key] = value
<39> highestKey = key
<40> </s>
|
===========below chunk 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
emptyDict = {**emptyDict, **maxDictPair}
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
logger.debug(f"The new sorted prob table is {emptyDict}")
return emptyDict
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
newSort(newDict)
at: collections.OrderedDict
items() -> _OrderedDictItemsView[_KT, _VT]
|
ciphey.__main__/Ciphey.produceProbTable
|
Modified
|
Ciphey~Ciphey
|
00ff24b1cc764c333dc016afe27ba3cbf3eda345
|
Prob table is now fully sorted
|
<13>:<add> sortedDic = {}
<19>:<add> valInt = round(self.mh.percentage(value, 1), 2)
<del> val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
<23>:<add> sortedDic[keyStr] = valInt
<24>:<add> f"The value as percentage is {valInt} and key is {keyStr}"
<del> f"The value as percentage is {val_as_percent} and key is {keyStr}"
<26>:<add> sortedDic = {
<add> k: v
<add> for k, v in sorted(
<add> sortedDic.items(), key=lambda item: item[1], reverse=True
<add> )
<add> }
<add> for k, v in sortedDic.items():
<add> table.add_row(k, str(v) + "%")
<del> table.add_row(keyStr, val_as_percent)
|
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
<0> """Produces the probability table using Rich's API
<1>
<2> :probTable: the probability distribution table returned by the neural network
<3> :returns: Nothing, it prints out the prob table.
<4>
<5> """
<6> logger.debug(f"Producing log table")
<7> table = Table(show_header=True, header_style="bold magenta")
<8> table.add_column("Name of Cipher")
<9> table.add_column("Probability", justify="right")
<10> # for every key, value in dict add a row
<11> # I think key is self.caesarcipher and not "caesar cipher"
<12> # i must callName() somewhere else in this code
<13> for k, v in probTable.items():
<14> for key, value in v.items():
<15> # Prevents the table from showing pointless 0.01 probs as they're faked
<16> if value == 0.01:
<17> continue
<18> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<19> val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
<20> keyStr = str(key).capitalize()
<21> if "Base" in keyStr:
<22> keyStr = keyStr[0:-2]
<23> logger.debug(
<24> f"The value as percentage is {val_as_percent} and key is {keyStr}"
<25> )
<26> table.add_row(keyStr, val_as_percent)
<27> self.console.print(table)
<28>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.mh = mh.mathsHelper()
self.console = Console()
at: ciphey.mathsHelper.mathsHelper
percentage(part, whole)
at: collections.OrderedDict
update = __update = _collections_abc.MutableMapping.update
update = __update = _collections_abc.MutableMapping.update
items() -> _OrderedDictItemsView[_KT, _VT]
__ne__ = _collections_abc.MutableMapping.__ne__
__marker = object()
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
emptyDict = {}
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
counterMax = 0
counterProb = len(probTable)
+ while counterMax < counterProb:
- while counterMax <= counterProb:
maxOverall = 0
highestKey = None
logger.debug(
f"Running while loop in sortProbTable, counterMax is {counterMax}"
)
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
logger.debug(
f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
)
maxLocal = maxLocal + value2
logger.debug(
f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
)
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table</s>
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s>
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
emptyDict = {**emptyDict, **maxDictPair}
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
logger.debug(f"The new sorted prob table is {emptyDict}")
return emptyDict
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
00ff24b1cc764c333dc016afe27ba3cbf3eda345
|
Prob table is now fully sorted
|
<12>:<del>
<21>:<del>
<26>:<del> "-d",
<27>:<del> "--debug",
<28>:<del> help="Activates debug mode",
<29>:<del>
<30>:<del> required=False,
<31>:<add> "-d", "--debug", help="Activates debug mode", required=False,
|
# module: ciphey.__main__
def main():
<0> parser = argparse.ArgumentParser(
<1> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<2> Examples:
<3> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<4> """
<5> )
<6> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<7> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<8> parser.add_argument(
<9> "-g",
<10> "--greppable",
<11> help="Only output the answer, no progress bars or information. Useful for grep",
<12>
<13> required=False,
<14> )
<15> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<16> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<17> parser.add_argument(
<18> "-c",
<19> "--printcipher",
<20> help="Do you want information on the cipher used?",
<21>
<22> required=False,
<23> )
<24>
<25> parser.add_argument(
<26> "-d",
<27> "--debug",
<28> help="Activates debug mode",
<29>
<30> required=False,
<31> )
<32> args = vars(parser.parse_args())
<33> if args["printcipher"] != None:
<34> cipher = True
<35> else:
<36> cipher = False
<37> if args["greppable"] != None:
<38> greppable = True
<39> else:
<40> greppable = False
<41> if args["debug"] != None:</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
debug = True
else:
debug = False
if args["text"]:
cipherObj = Ciphey(args["text"], greppable, cipher, debug)
cipherObj.decrypt()
else:
print("No arguments were supplied. Look at the help menu with -h or --help")
===========unchanged ref 0===========
at: argparse
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: ciphey.__main__
Ciphey(text, grep=False, cipher=False, debug=False)
at: ciphey.__main__.Ciphey
decrypt()
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
"""Produces the probability table using Rich's API
:probTable: the probability distribution table returned by the neural network
:returns: Nothing, it prints out the prob table.
"""
logger.debug(f"Producing log table")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name of Cipher")
table.add_column("Probability", justify="right")
# for every key, value in dict add a row
# I think key is self.caesarcipher and not "caesar cipher"
# i must callName() somewhere else in this code
+ sortedDic = {}
for k, v in probTable.items():
for key, value in v.items():
# Prevents the table from showing pointless 0.01 probs as they're faked
if value == 0.01:
continue
logger.debug(f"Key is {str(key)} and value is {str(value)}")
+ valInt = round(self.mh.percentage(value, 1), 2)
- val_as_percent = str(round(self.mh.percentage(value, 1), 2)) + "%"
keyStr = str(key).capitalize()
if "Base" in keyStr:
keyStr = keyStr[0:-2]
+ sortedDic[keyStr] = valInt
logger.debug(
+ f"The value as percentage is {valInt} and key is {keyStr}"
- f"The value as percentage is {val_as_percent} and key is {keyStr}"
)
+ sortedDic = {
+ k: v
+ for k, v in sorted(
+ sortedDic.items(), key=lambda item: item[1], reverse=True
+ )
+ </s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
# offset: 1
<s>
+ sortedDic.items(), key=lambda item: item[1], reverse=True
+ )
+ }
+ for k, v in sortedDic.items():
+ table.add_row(k, str(v) + "%")
- table.add_row(keyStr, val_as_percent)
self.console.print(table)
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
"""Sorts the probabiltiy table"""
# for each object: prob table in dictionary
maxOverall = 0
maxDictPair = {}
highestKey = None
emptyDict = {}
# sorts the prob table before we find max, and converts it to order dicts
for key, value in probTable.items():
probTable[key] = self.newSort(value)
probTable[key] = dict(probTable[key])
# gets maximum key then sets it to the front
counterMax = 0
counterProb = len(probTable)
+ while counterMax < counterProb:
- while counterMax <= counterProb:
maxOverall = 0
highestKey = None
logger.debug(
f"Running while loop in sortProbTable, counterMax is {counterMax}"
)
for key, value in probTable.items():
logger.debug(f"Sorting {key}")
maxLocal = 0
# for each item in that table
for key2, value2 in value.items():
logger.debug(
f"Running key2 {key2}, value2 {value2} for loop for {value.items()}"
)
maxLocal = maxLocal + value2
logger.debug(
f"MaxLocal is {maxLocal} and maxOverall is {maxOverall}"
)
if maxLocal > maxOverall:
logger.debug(f"New max local found {maxLocal}")
# because the dict doesnt reset
maxDictPair = {}
maxOverall = maxLocal
# so eventually, we get the maximum dict pairing?
maxDictPair[key] = value
highestKey = key
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table</s>
===========changed ref 3===========
# module: ciphey.mathsHelper
class mathsHelper:
def sortProbTable(self, probTable):
# offset: 1
<s>
logger.debug(f"Highest key is {highestKey}")
# removes the highest key from the prob table
logger.debug(f"Prob table is {probTable} and highest key is {highestKey}")
logger.debug(f"Removing {probTable[highestKey]}")
del probTable[highestKey]
logger.debug(f"Prob table after deletion is {probTable}")
counterMax += 1
emptyDict = {**emptyDict, **maxDictPair}
# returns the max dict (at the start) with the prob table
# this way, it should always work on most likely first.
logger.debug(
f"The prob table is {probTable} and the maxDictPair is {maxDictPair}"
)
logger.debug(f"The new sorted prob table is {emptyDict}")
return emptyDict
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
ec81fd8162b7418310a6f966a0cc636697eb5228
|
Logging has a bug where it displays debug info
|
<35>:<del> for key, value in self.whatToChoose.items():
<36>:<del> self.whatToChoose[key] = self.
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<2> self.whatToChoose = {
<3> self.hash: {
<4> "sha1": self.probabilityDistribution[0],
<5> "md5": self.probabilityDistribution[1],
<6> "sha256": self.probabilityDistribution[2],
<7> "sha512": self.probabilityDistribution[3],
<8> },
<9> self.basic: {"caesar": self.probabilityDistribution[4]},
<10> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<11> self.encoding: {
<12> "reverse": self.probabilityDistribution[6],
<13> "base64": self.probabilityDistribution[7],
<14> "binary": self.probabilityDistribution[8],
<15> "hexadecimal": self.probabilityDistribution[9],
<16> "ascii": self.probabilityDistribution[10],
<17> "morse": self.probabilityDistribution[11],
<18> },
<19> }
<20>
<21> logger.debug(
<22> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<23> )
<24>
<25> # sorts each indiviudal sub-dictionary
<26> for key, value in self.whatToChoose.items():
<27> for k, v in value.items():
<28> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<29> if v < 0.01:
<30> self.whatToChoose[key][k] = 0.01
<31> logger.debug(
<32> f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
<33> )
<34>
<35> for key, value in self.whatToChoose.items():
<36> self.whatToChoose[key] = self.</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# the below code selects the most likely one
# and places it at the front
# TODO is this code redundant because of self.mh.sortProbTable?
new_dict = {}
maximum = 0.00
max_key = None
max_val = None
for key, value in self.whatToChoose.items():
val = next(iter(value))
val = value[val]
if val >= maximum:
maximum = val
max_key = key
max_val = value
new_dict = collections.OrderedDict()
new_dict[max_key] = max_val
for key, value in self.whatToChoose.items():
if key == max_key:
continue
new_dict[key] = value
# Creates and prints the probability table
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(new_dict)
self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
</s>
===========below chunk 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s>Contents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey
one_level_of_decryption(self, file=None, sickomode=None)
one_level_of_decryption(file=None, sickomode=None)
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.mh = mh.mathsHelper()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
self.level = 1
self.sickomode = False
self.greppable = grep
at: ciphey.mathsHelper.mathsHelper
percentage(part, whole)
at: mathsHelper.mathsHelper
sortProbTable(probTable)
at: neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
===========changed ref 0===========
# module: ciphey.test_encoding
+ logger.remove()
===========changed ref 1===========
# module: ciphey.test_neuralNetwork
+ logger.remove()
===========changed ref 2===========
# module: ciphey.test_integration
+ logger.remove()
===========changed ref 3===========
# module: ciphey.test_chi_squared
+ logger.remove()
===========changed ref 4===========
# module: ciphey.test_basicparent
+ logger.remove()
try:
from languageCheckerMod import LanguageChecker as lcm
except ModuleNotFoundError:
from app.languageCheckerMod import LanguageChecker as lcm
try:
from Decryptor.basicEncryption.basic_parent import BasicParent
except ModuleNotFoundError:
from app.Decryptor.basicEncryption.basic_parent import BasicParent
|
ciphey.__main__/Ciphey.produceProbTable
|
Modified
|
Ciphey~Ciphey
|
ec81fd8162b7418310a6f966a0cc636697eb5228
|
Logging has a bug where it displays debug info
|
<25>:<del> logger.debug(
<26>:<add> logger.debug(f"The value as percentage is {valInt} and key is {keyStr}")
<del> f"The value as percentage is {valInt} and key is {keyStr}"
<27>:<del> )
|
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
<0> """Produces the probability table using Rich's API
<1>
<2> :probTable: the probability distribution table returned by the neural network
<3> :returns: Nothing, it prints out the prob table.
<4>
<5> """
<6> logger.debug(f"Producing log table")
<7> table = Table(show_header=True, header_style="bold magenta")
<8> table.add_column("Name of Cipher")
<9> table.add_column("Probability", justify="right")
<10> # for every key, value in dict add a row
<11> # I think key is self.caesarcipher and not "caesar cipher"
<12> # i must callName() somewhere else in this code
<13> sortedDic = {}
<14> for k, v in probTable.items():
<15> for key, value in v.items():
<16> # Prevents the table from showing pointless 0.01 probs as they're faked
<17> if value == 0.01:
<18> continue
<19> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<20> valInt = round(self.mh.percentage(value, 1), 2)
<21> keyStr = str(key).capitalize()
<22> if "Base" in keyStr:
<23> keyStr = keyStr[0:-2]
<24> sortedDic[keyStr] = valInt
<25> logger.debug(
<26> f"The value as percentage is {valInt} and key is {keyStr}"
<27> )
<28> sortedDic = {
<29> k: v
<30> for k, v in sorted(
<31> sortedDic.items(), key=lambda item: item[1], reverse=True
<32> )
<33> }
<34> for k, v in sortedDic.items():
<35> table.add_row(k, str</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def produceProbTable(self, probTable):
# offset: 1
self.console.print(table)
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.text = text
self.greppable = grep
self.cipher = cipher
self.console = Console()
at: ciphey.__main__.Ciphey.decrypt
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
at: ciphey.__main__.Ciphey.produceProbTable
table = Table(show_header=True, header_style="bold magenta")
valInt = round(self.mh.percentage(value, 1), 2)
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
- for key, value in self.whatToChoose.items():
- self.whatToChoose[key] = self.mh.sortDictionary(value)
-
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>(value)
-
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
-
- # the below code selects the most likely one
- # and places it at the front
- # TODO is this code redundant because of self.mh.sortProbTable?
- new_dict = {}
- maximum = 0.00
- max_key = None
- max_val = None
- for key, value in self.whatToChoose.items():
- val = next(iter(value))
- val = value[val]
- if val >= maximum:
- maximum = val
- max_key = key
- max_val = value
- new_dict = collections.OrderedDict()
- new_dict[max_key] = max_val
- for key, value in self.whatToChoose.items():
- if key == max_key:
- continue
- new_dict[key] = value
# Creates and prints the probability table
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
+ self.produceProbTable(self.whatToChoose)
- self.produceProbTable(new_dict)
- self.whatToChoose = new_dict
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 2
<s> self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========changed ref 3===========
# module: ciphey.test_encoding
+ logger.remove()
===========changed ref 4===========
# module: ciphey.test_neuralNetwork
+ logger.remove()
===========changed ref 5===========
# module: ciphey.test_integration
+ logger.remove()
===========changed ref 6===========
# module: ciphey.test_chi_squared
+ logger.remove()
===========changed ref 7===========
# module: ciphey.test_basicparent
+ logger.remove()
try:
from languageCheckerMod import LanguageChecker as lcm
except ModuleNotFoundError:
from app.languageCheckerMod import LanguageChecker as lcm
try:
from Decryptor.basicEncryption.basic_parent import BasicParent
except ModuleNotFoundError:
from app.Decryptor.basicEncryption.basic_parent import BasicParent
|
ciphey.test_basicparent/TestBasicParent.test_viginere_yes
|
Modified
|
Ciphey~Ciphey
|
342c1f6f45209a2c3f6b3f332ddc81a9c7227b7a
|
Fixed viginere test
|
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
<0> lc = lcm.LanguageChecker()
<1> bp = BasicParent(lc)
<2> result = bp.decrypt(
<3> """Adiz Avtzqeci Tmzubb wsa m Pmilqev halpqavtakuoi, lgouqdaf, kdmktsvmztsl, izr xoexghzr kkusitaaf. Vz wsa twbhdg ubalmmzhdad qz hce vmhsgohuqbo ox kaakulmd gxiwvos, krgdurdny i rcmmstugvtawz ca tzm ocicwxfg jf "stscmilpy" oid "uwydptsbuci" wabt hce Lcdwig eiovdnw. Bgfdny qe kddwtk qjnkqpsmev ba pz tzm roohwz at xoexghzr kkusicw izr vrlqrwxist uboedtuuznum. Pimifo Icmlv Emf DI, Lcdwig owdyzd xwd hce Ywhsmnemzh Xovm mby Cqxtsm Supacg (GUKE) oo Bdmfqclwg Bomk, Tzuhvif'a ocyetzqofifo ositjm. Rcm a lqys ce oie vzav wr Vpt 8, lpq gzclqab mekxabnittq tjr Ymdavn fihog cjgbhvnstkgds. Zm psqikmp o iuejqf jf lmoviiicqg aoj jdsvkavs Uzreiz qdpzmdg, dnutgrdny bts helpar jf lpq pjmtm, mb zlwkffjmwktoiiuix avczqzs ohsb ocplv nuby swbfwigk naf ohw Mzwbms umqcifm. Mtoej bts raj pq kjrcmp oo tzm Zooig</s>
|
===========below chunk 0===========
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
# offset: 1
)
self.assertEqual(result["IsPlaintext?"], True)
===========unchanged ref 0===========
at: Decryptor.basicEncryption.basic_parent
BasicParent(lc)
at: Decryptor.basicEncryption.basic_parent.BasicParent
decrypt(text)
at: languageCheckerMod.LanguageChecker
LanguageChecker()
|
|
ciphey.test_basicparent/TestBasicParent.test_viginere_yes
|
Modified
|
Ciphey~Ciphey
|
9f5de04a285710948a4b69d6940c495620af482c
|
Writing tests
|
<0>:<del> lc = lcm.LanguageChecker()
<1>:<del> bp = BasicParent(lc)
<2>:<del> result = bp.decrypt(
<3>:<del> """Adiz Avtzqeci Tmzubb wsa m Pmilqev halpqavtakuoi, lgouqdaf, kdmktsvmztsl, izr xoexghzr kkusitaaf. Vz wsa twbhdg ubalmmzhdad qz hce vmhsgohuqbo ox kaakulmd gxiwvos, krgdurdny i rcmmstugvtawz ca tzm ocicwxfg jf "stscmilpy" oid "uwydptsbuci" wabt hce Lcdwig eiovdnw. Bgfdny qe kddwtk qjnkqpsmev ba pz tzm roohwz at xoexghzr kkusicw izr vrlqrwxist uboedtuuznum. Pimifo Icmlv Emf DI, Lcdwig owdyzd xwd hce Ywhsmnemzh Xovm mby Cqxtsm Supacg (GUKE) oo Bdmfqclwg Bomk, Tzuhvif'a ocyetzqofifo ositjm. Rcm a lqys ce oie vzav wr Vpt 8, lpq gzclqab mekxabnittq tjr Ymdavn fihog cjgbhvnstkgds. Zm psqikmp o iuejqf jf lmoviiicqg aoj jdsvkavs Uzreiz qdpzmdg, dnutgrdny bts helpar jf lpq pjmtm, mb zlwkffjmwktoiiuix avczqzs ohsb ocplv nuby swbfwigk naf ohw Mzwbms umqcifm. Mtoej bts raj pq kjrcmp oo tzm Zooig
|
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
<0> lc = lcm.LanguageChecker()
<1> bp = BasicParent(lc)
<2> result = bp.decrypt(
<3> """Adiz Avtzqeci Tmzubb wsa m Pmilqev halpqavtakuoi, lgouqdaf, kdmktsvmztsl, izr xoexghzr kkusitaaf. Vz wsa twbhdg ubalmmzhdad qz hce vmhsgohuqbo ox kaakulmd gxiwvos, krgdurdny i rcmmstugvtawz ca tzm ocicwxfg jf "stscmilpy" oid "uwydptsbuci" wabt hce Lcdwig eiovdnw. Bgfdny qe kddwtk qjnkqpsmev ba pz tzm roohwz at xoexghzr kkusicw izr vrlqrwxist uboedtuuznum. Pimifo Icmlv Emf DI, Lcdwig owdyzd xwd hce Ywhsmnemzh Xovm mby Cqxtsm Supacg (GUKE) oo Bdmfqclwg Bomk, Tzuhvif'a ocyetzqofifo ositjm. Rcm a lqys ce oie vzav wr Vpt 8, lpq gzclqab mekxabnittq tjr Ymdavn fihog cjgbhvnstkgds. Zm psqikmp o iuejqf jf lmoviiicqg aoj jdsvkavs Uzreiz qdpzmdg, dnutgrdny bts helpar jf lpq pjmtm, mb zlwkffjmwktoiiuix avczqzs ohsb ocplv nuby swbfwigk naf ohw Mzwbms umqcifm. Mtoej bts raj pq kjrcmp oo tzm Zooig</s>
|
===========below chunk 0===========
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
# offset: 1
)
self.assertEqual(True, True)
===========unchanged ref 0===========
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
|
ciphey.test_integration/testIntegration.test_chi_maxima_false
|
Modified
|
Ciphey~Ciphey
|
9f5de04a285710948a4b69d6940c495620af482c
|
Writing tests
|
# module: ciphey.test_integration
class testIntegration(unittest.TestCase):
def test_chi_maxima_false(self):
<0> lc = LanguageChecker.LanguageChecker()
<1> result = lc.checkLanguage("The quick brown fox jumped over the lazy dog")
<2> result = lc.checkLanguage(
<3> "Hypertext Transfer Protocol (HTTP) parameters, including HTTP headers, allow the client and the server to pass additional information with the request or the response."
<4> )
<5> result = lc.checkLanguage(
<6> "Hypertext Transfer Protocol (HTTP) parameters, including HTTP headers, allow the client and the server to pass additional information with the request or the response."
<7> )
<8> result = lc.checkLanguage(
<9> "HTTP parameters and headers can often reveal information about how a web application is transmitting data and storing cookies. Clients send parameters including the user agent of the browser."
<10> )
<11> result = lc.checkLanguage(
<12> "You probably build websites and think your shit is special. You think your 13 megabyte parallax-ative home page is going to get you some fucking Awwward banner you can glue to the top corner of your site. You think your 40-pound jQuery file and 83 polyfills give IE7 a boner because it finally has box-shadow. Wrong, motherfucker. Let me describe your perfect-ass website:"
<13> )
<14> result = lc.checkLanguage(
<15> "You. Are. Over-designing. Look at this shit. It's a motherfucking website. Why the fuck do you need to animate a fucking trendy-ass banner flag when I hover over that useless piece of shit? You spent hours on it and added 80 kilobytes to your fucking site, and some motherfucker jabbing at it on their iPad with fat sausage fingers will never see that shit. Not to mention blind people will never see that shit, but they don't see any of your shitty shit."
<16> )
<17> result = lc.checkLanguage(
<18> "This entire page weighs less than the gradient</s>
|
===========below chunk 0===========
# module: ciphey.test_integration
class testIntegration(unittest.TestCase):
def test_chi_maxima_false(self):
# offset: 1
)
result = lc.checkLanguage(
"You dumbass. You thought you needed media queries to be responsive, but no. Responsive means that it responds to whatever motherfucking screensize it's viewed on. This site doesn't care if you're on an iMac or a motherfucking Tamagotchi."
)
result = lc.checkLanguage(
"Like the man who's never grown out his beard has no idea what his true natural state is, you have no fucking idea what a website is. All you have ever seen are shitty skeuomorphic bastardizations of what should be text communicating a fucking message. This is a real, naked website. Look at it. It's fucking beautiful."
)
result = lc.checkLanguage(
"Have you guys noticed that sometimes the foremost academic websites with lots of scientific information tend to look like this?"
)
result = lc.checkLanguage(
"That's because academics do Save as Website from Microsoft Word and call it a day."
)
result = lc.checkLanguage(
"In case anyone was interested, fuck is used 33 times in the page."
)
result = lc.checkLanguage(
"Hi! I just checked this URL and it appeared to be unavailable or slow loading (Connection timed out after 8113 milliseconds). Here are some mirrors to try:"
)
result = lc.checkLanguage("The quick brown fox jumped over the lazy dog")
self.assertEqual(result, False)
===========unchanged ref 0===========
at: languageCheckerMod.LanguageChecker
LanguageChecker()
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
===========changed ref 0===========
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
- lc = lcm.LanguageChecker()
- bp = BasicParent(lc)
- result = bp.decrypt(
- """Adiz Avtzqeci Tmzubb wsa m Pmilqev halpqavtakuoi, lgouqdaf, kdmktsvmztsl, izr xoexghzr kkusitaaf. Vz wsa twbhdg ubalmmzhdad qz hce vmhsgohuqbo ox kaakulmd gxiwvos, krgdurdny i rcmmstugvtawz ca tzm ocicwxfg jf "stscmilpy" oid "uwydptsbuci" wabt hce Lcdwig eiovdnw. Bgfdny qe kddwtk qjnkqpsmev ba pz tzm roohwz at xoexghzr kkusicw izr vrlqrwxist uboedtuuznum. Pimifo Icmlv Emf DI, Lcdwig owdyzd xwd hce Ywhsmnemzh Xovm mby Cqxtsm Supacg (GUKE) oo Bdmfqclwg Bomk, Tzuhvif'a ocyetzqofifo ositjm. Rcm a lqys ce oie vzav wr Vpt 8, lpq gzclqab mekxabnittq tjr Ymdavn fihog cjgbhvnstkgds. Zm psqikmp o iuejqf jf lmoviiicqg aoj jdsvkavs Uzreiz qdpzmdg, dnutgrdny bts helpar jf lpq pjmtm, mb zlwkffjmwktoiiuix avczqzs ohsb ocplv nuby swbfwigk naf ohw Mzwbms umqcifm. Mtoej bts raj pq kjrcmp oo tzm Zooig</s>
===========changed ref 1===========
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
# offset: 1
<s> ohw Mzwbms umqcifm. Mtoej bts raj pq kjrcmp oo tzm Zooigvmz Khqauqvl Dincmalwdm, rhwzq vz cjmmhzd gvq ca tzm rwmsl lqgdgfa rcm a kbafzd-hzaumae kaakulmd, hce SKQ. Wi 1948 Tmzubb jgqzsy Msf Zsrmsv'e Qjmhcfwig Dincmalwdm vt Eizqcekbqf Pnadqfnilg, ivzrw pq onsaafsy if bts yenmxckmwvf ca tzm Yoiczmehzr uwydptwze oid tmoohe avfsmekbqr dn eifvzmsbuqvl tqazjgq. Pq kmolm m dvpwz ab ohw ktshiuix pvsaa at hojxtcbefmewn, afl bfzdakfsy okkuzgalqzu xhwuuqvl jmmqoigve gpcz ie hce Tmxcpsgd-Lvvbgbubnkq zqoxtawz, kciup isme xqdgo otaqfqev qz hce 1960k. Bgfdny'a tchokmjivlabk fzsmtfsy if i ofdmavmz krgaqqptawz wi 1952, wzmz vjmgaqlpad iohn wwzq goidt uzgeyix wi tzm Gbdtwl Wwigvwy. Vz aukqdoev bdsvtemzh rilp rshadm tcmmgvqg (xhwuuqvl uiehmalqab) vs sv mzoejvmhdvw ba dmikwz. Hpravs rdev</s>
===========changed ref 2===========
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_viginere_yes(self):
# offset: 2
<s> 1954, xpsl whsm tow iszkk jqtjrw pug 42id tqdhcdsg, rfjm ugmbddw xawnofqzu. Vn avcizsl lqhzreqzsy tzif vds vmmhc wsa eidcalq; vds ewfvzr svp gjmw wfvzrk jqzdenmp vds vmmhc wsa mqxivmzhvl. Gv 10 Esktwunsm 2009, fgtxcrifo mb Dnlmdbzt uiydviyv, Nfdtaat Dmiem Ywiikbqf Bojlab Wrgez avdw iz cafakuog pmjxwx ahwxcby gv nscadn at ohw Jdwoikp scqejvysit xwd "hce sxboglavs kvy zm ion tjmmhzd." Sa at Haq 2012 i bfdvsbq azmtmd'g widt ion bwnafz tzm Tcpsw wr Zjrva ivdcz eaigd yzmbo Tmzubb a kbmhptgzk dvrvwz wa efiohzd."""
- )
self.assertEqual(True, True)
|
|
ciphey.test_integration/testIntegration.test_chi_maxima
|
Modified
|
Ciphey~Ciphey
|
f8648d94ee28d71d1568b36efe477237475b602f
|
All tests now succee
|
# module: ciphey.test_integration
class testIntegration(unittest.TestCase):
def test_chi_maxima(self):
<0> lc = LanguageChecker.LanguageChecker()
<1> result = lc.checkLanguage("The quick brown fox jumped over the lazy dog")
<2> result = lc.checkLanguage(
<3> "Hypertext Transfer Protocol (HTTP) parameters, including HTTP headers, allow the client and the server to pass additional information with the request or the response."
<4> )
<5> result = lc.checkLanguage(
<6> "Hypertext Transfer Protocol (HTTP) parameters, including HTTP headers, allow the client and the server to pass additional information with the request or the response."
<7> )
<8> result = lc.checkLanguage(
<9> "HTTP parameters and headers can often reveal information about how a web application is transmitting data and storing cookies. Clients send parameters including the user agent of the browser."
<10> )
<11> result = lc.checkLanguage(
<12> "You probably build websites and think your shit is special. You think your 13 megabyte parallax-ative home page is going to get you some fucking Awwward banner you can glue to the top corner of your site. You think your 40-pound jQuery file and 83 polyfills give IE7 a boner because it finally has box-shadow. Wrong, motherfucker. Let me describe your perfect-ass website:"
<13> )
<14> result = lc.checkLanguage(
<15> "You. Are. Over-designing. Look at this shit. It's a motherfucking website. Why the fuck do you need to animate a fucking trendy-ass banner flag when I hover over that useless piece of shit? You spent hours on it and added 80 kilobytes to your fucking site, and some motherfucker jabbing at it on their iPad with fat sausage fingers will never see that shit. Not to mention blind people will never see that shit, but they don't see any of your shitty shit."
<16> )
<17> result = lc.checkLanguage(
<18> "This entire page weighs less than the gradient-mesh</s>
|
===========below chunk 0===========
# module: ciphey.test_integration
class testIntegration(unittest.TestCase):
def test_chi_maxima(self):
# offset: 1
)
result = lc.checkLanguage(
"You dumbass. You thought you needed media queries to be responsive, but no. Responsive means that it responds to whatever motherfucking screensize it's viewed on. This site doesn't care if you're on an iMac or a motherfucking Tamagotchi."
)
result = lc.checkLanguage(
"Like the man who's never grown out his beard has no idea what his true natural state is, you have no fucking idea what a website is. All you have ever seen are shitty skeuomorphic bastardizations of what should be text communicating a fucking message. This is a real, naked website. Look at it. It's fucking beautiful."
)
result = lc.checkLanguage(
"Have you guys noticed that sometimes the foremost academic websites with lots of scientific information tend to look like this?"
)
result = lc.checkLanguage(
"That's because academics do Save as Website from Microsoft Word and call it a day."
)
result = lc.checkLanguage(
"In case anyone was interested, fuck is used 33 times in the page."
)
result = lc.checkLanguage(
"Hi! I just checked this URL and it appeared to be unavailable or slow loading (Connection timed out after 8113 milliseconds). Here are some mirrors to try:"
)
result = lc.checkLanguage("The quick brown fox jumped over the lazy dog")
self.assertEqual(result, False)
===========unchanged ref 0===========
at: languageCheckerMod.LanguageChecker
LanguageChecker()
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
|
|
ciphey.test_basicparent/TestBasicParent.test_basic_parent_reverse_yes_2
|
Modified
|
Ciphey~Ciphey
|
d0b638e00c8ca3fea17f0a7b2f186d989f3c5165
|
Tests written for transposition
|
<5>:<add> self.assertequal(result["isplaintext?"], true)
<del> self.assertEqual(result["IsPlaintext?"], True)
|
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_basic_parent_reverse_yes_2(self):
<0> lc = lcm.LanguageChecker()
<1> bp = BasicParent(lc)
<2> result = bp.decrypt(
<3> "sevom ylpmis rac eht ciffart ruoy lla gnillenut si hcihw redivorp NPV a ekilnU"
<4> )
<5> self.assertEqual(result["IsPlaintext?"], True)
<6>
|
===========unchanged ref 0===========
at: Decryptor.basicEncryption.basic_parent
BasicParent(lc)
at: Decryptor.basicEncryption.basic_parent.BasicParent
decrypt(text)
at: languageCheckerMod.LanguageChecker
LanguageChecker()
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
fc05f85818dceedee4b7973080b740d79a780b41
|
Added better argument parsing support
|
<0>:<add>
<12>:<add> action="store_true",
<20>:<add> action="store_true",
<22>:<add> # fake argument to stop argparser complaining about no arguments
<add> # allows sys.argv to be used
<add> parser.add_argument("-m", action="store_false", default=True, required=False)
<24>:<add> "-d",
<add> "--debug",
<add> help="Activates debug mode",
<add> required=False,
<add> action="store_true",
<del> "-d", "--debug", help="Activates debug mode", required=False,
<26>:<add> parser.add_argument("rest", nargs=argparse.REMAINDER)
<27>:<add> if args["printcipher"]:
<del> if args["printcipher"] != None:
<31>:<add> if args["greppable"]:
<del> if args["greppable"] != None:
<35>:<add> if args["debug"]:
<del> if args["debug"] != None:
|
# module: ciphey.__main__
def main():
<0> parser = argparse.ArgumentParser(
<1> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<2> Examples:
<3> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<4> """
<5> )
<6> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<7> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<8> parser.add_argument(
<9> "-g",
<10> "--greppable",
<11> help="Only output the answer, no progress bars or information. Useful for grep",
<12> required=False,
<13> )
<14> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<15> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<16> parser.add_argument(
<17> "-c",
<18> "--printcipher",
<19> help="Do you want information on the cipher used?",
<20> required=False,
<21> )
<22>
<23> parser.add_argument(
<24> "-d", "--debug", help="Activates debug mode", required=False,
<25> )
<26> args = vars(parser.parse_args())
<27> if args["printcipher"] != None:
<28> cipher = True
<29> else:
<30> cipher = False
<31> if args["greppable"] != None:
<32> greppable = True
<33> else:
<34> greppable = False
<35> if args["debug"] != None:
<36> debug = True
<37> else:
<38> debug = False
<39>
</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
cipherObj = Ciphey(args["text"], greppable, cipher, debug)
cipherObj.decrypt()
else:
print("No arguments were supplied. Look at the help menu with -h or --help")
===========unchanged ref 0===========
at: argparse
REMAINDER = '...'
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
e551c966be5e4cbe6e7c88f0d77ac341bcbb8844
|
Fixed a bug
|
# module: ciphey.__main__
def main():
<0>
<1> parser = argparse.ArgumentParser(
<2> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<3> Examples:
<4> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<5> """
<6> )
<7> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<8> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<9> parser.add_argument(
<10> "-g",
<11> "--greppable",
<12> help="Only output the answer, no progress bars or information. Useful for grep",
<13> action="store_true",
<14> required=False,
<15> )
<16> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<17> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<18> parser.add_argument(
<19> "-c",
<20> "--printcipher",
<21> help="Do you want information on the cipher used?",
<22> action="store_true",
<23> required=False,
<24> )
<25> # fake argument to stop argparser complaining about no arguments
<26> # allows sys.argv to be used
<27> parser.add_argument("-m", action="store_false", default=True, required=False)
<28>
<29> parser.add_argument(
<30> "-d",
<31> "--debug",
<32> help="Activates debug mode",
<33> required=False,
<34> action="store_true",
<35> )
<36> parser.add_argument("rest", nargs=argparse.REMAINDER)</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
args = vars(parser.parse_args())
if args["printcipher"]:
cipher = True
else:
cipher = False
if args["greppable"]:
greppable = True
else:
greppable = False
if args["debug"]:
debug = True
else:
debug = False
text = None
if args["text"]:
text = args["text"]
if len(sys.argv) == 1:
print("No arguments were supplied. Look at the help menu with -h or --help")
elif args["text"] == None and len(sys.argv) > 1:
text = args["rest"][0]
print(f"text is {text}")
if not sys.stdin.isatty():
text = str(sys.stdin.read())
print(text)
if text != None:
cipherObj = Ciphey(text, greppable, cipher, debug)
cipherObj.decrypt()
===========unchanged ref 0===========
at: argparse
REMAINDER = '...'
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: sys
argv: List[str]
stdin: TextIO
at: typing.IO
__slots__ = ()
isatty() -> bool
|
|
ciphey.test_basicparent/TestBasicParent.test_basic_parent_reverse_yes_2
|
Modified
|
Ciphey~Ciphey
|
e329af2b62c0c5f0e1063294b2e6becd14be635d
|
All tests run
|
<5>:<add> self.assertEqual(result["IsPlaintext?"], True)
<del> self.assertequal(result["isplaintext?"], true)
|
# module: ciphey.test_basicparent
class TestBasicParent(unittest.TestCase):
def test_basic_parent_reverse_yes_2(self):
<0> lc = lcm.LanguageChecker()
<1> bp = BasicParent(lc)
<2> result = bp.decrypt(
<3> "sevom ylpmis rac eht ciffart ruoy lla gnillenut si hcihw redivorp NPV a ekilnU"
<4> )
<5> self.assertequal(result["isplaintext?"], true)
<6>
|
===========unchanged ref 0===========
at: Decryptor.basicEncryption.basic_parent
BasicParent(lc)
at: Decryptor.basicEncryption.basic_parent.BasicParent
decrypt(text)
at: languageCheckerMod.LanguageChecker
LanguageChecker()
at: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
|
ciphey.Decryptor.basicEncryption.basic_parent/BasicParent.decrypt
|
Modified
|
Ciphey~Ciphey
|
9d1bd1087bd2f7573518eadfe15314d07dde7ad0
|
Merge pull request #71 from brandonskerritt/SwitchingToRich
|
<17>:<add> # so i just run it last lol]
<del> # so i just run it last lol
<18>:<add> """
<27>:<add> }"""
<del> }
|
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
<0> self.text = text
<1> from multiprocessing.dummy import Pool as ThreadPool
<2>
<3> pool = ThreadPool(4)
<4> answers = pool.map(self.callDecrypt, self.list_of_objects)
<5>
<6> """for item in self.list_of_objects:
<7> result = item.decrypt(text)
<8> answers.append(result)"""
<9> for answer in answers:
<10> # adds the LC objects together
<11> self.lc = self.lc + answer["lc"]
<12> if answer["IsPlaintext?"]:
<13> return answer
<14>
<15> # so viginere runs ages
<16> # and you cant kill threads in a pool
<17> # so i just run it last lol
<18> result = self.callDecrypt(self.viginere)
<19> if result["IsPlaintext?"]:
<20> return result
<21> return {
<22> "lc": self.lc,
<23> "IsPlaintext?": False,
<24> "Plaintext": None,
<25> "Cipher": None,
<26> "Extra Information": None,
<27> }
<28>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent
callDecrypt(obj)
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent.__init__
self.lc = lc
self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans]
at: multiprocessing.dummy
Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
97003efed68aac7f100315bc18c82bbd89444c29
|
Fixed poetry and added check before tex
|
<1>:<add> # checks to see if inputted text is plaintext
<add> result = self.lc.checkLanguage(self.text)
<add> if result:
<add> print("You inputted plain text!")
<add> return None
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<2> self.whatToChoose = {
<3> self.hash: {
<4> "sha1": self.probabilityDistribution[0],
<5> "md5": self.probabilityDistribution[1],
<6> "sha256": self.probabilityDistribution[2],
<7> "sha512": self.probabilityDistribution[3],
<8> },
<9> self.basic: {"caesar": self.probabilityDistribution[4]},
<10> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<11> self.encoding: {
<12> "reverse": self.probabilityDistribution[6],
<13> "base64": self.probabilityDistribution[7],
<14> "binary": self.probabilityDistribution[8],
<15> "hexadecimal": self.probabilityDistribution[9],
<16> "ascii": self.probabilityDistribution[10],
<17> "morse": self.probabilityDistribution[11],
<18> },
<19> }
<20>
<21> logger.debug(
<22> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<23> )
<24>
<25> # sorts each indiviudal sub-dictionary
<26> for key, value in self.whatToChoose.items():
<27> for k, v in value.items():
<28> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<29> if v < 0.01:
<30> self.whatToChoose[key][k] = 0.01
<31> logger.debug(
<32> f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
<33> )
<34>
<35> self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
<36>
<37> </s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(self.whatToChoose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey
produceProbTable(probTable)
one_level_of_decryption(file=None, sickomode=None)
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.lc = lc.LanguageChecker()
self.mh = mh.mathsHelper()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
self.level = 1
self.sickomode = False
self.greppable = grep
at: ciphey.mathsHelper.mathsHelper
sortProbTable(probTable)
at: ciphey.neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
97003efed68aac7f100315bc18c82bbd89444c29
|
Fixed poetry and added check before tex
|
# module: ciphey.__main__
def main():
<0>
<1> parser = argparse.ArgumentParser(
<2> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<3> Examples:
<4> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<5> """
<6> )
<7> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<8> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<9> parser.add_argument(
<10> "-g",
<11> "--greppable",
<12> help="Only output the answer, no progress bars or information. Useful for grep",
<13> action="store_true",
<14> required=False,
<15> )
<16> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<17> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<18> parser.add_argument(
<19> "-c",
<20> "--printcipher",
<21> help="Do you want information on the cipher used?",
<22> action="store_true",
<23> required=False,
<24> )
<25> # fake argument to stop argparser complaining about no arguments
<26> # allows sys.argv to be used
<27> parser.add_argument("-m", action="store_false", default=True, required=False)
<28>
<29> parser.add_argument(
<30> "-d",
<31> "--debug",
<32> help="Activates debug mode",
<33> required=False,
<34> action="store_true",
<35> )
<36> parser.add_argument("rest", nargs=argparse.REMAINDER)</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
args = vars(parser.parse_args())
if args["printcipher"]:
cipher = True
else:
cipher = False
if args["greppable"]:
greppable = True
else:
greppable = False
if args["debug"]:
debug = True
else:
debug = False
text = None
# the below text does:
# if -t is supplied, use that
# if ciphey is called like:
# ciphey 'encrypted text' use that
# else if data is piped like:
# echo 'hello' | ciphey use that
# if no data is supplied, no arguments supplied.
if args["text"]:
text = args["text"]
if args["text"] == None and len(sys.argv) > 1:
text = args["rest"][0]
print(f"text is {text}")
if not sys.stdin.isatty():
text = str(sys.stdin.read())
if len(sys.argv) == 1 and text == None:
print("No arguments were supplied. Look at the help menu with -h or --help")
if text != None:
cipherObj = Ciphey(text, greppable, cipher, debug)
cipherObj.decrypt()
===========unchanged ref 0===========
at: argparse
REMAINDER = '...'
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: sys
argv: List[str]
stdin: TextIO
at: typing.IO
__slots__ = ()
isatty() -> bool
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# Read the documentation for more on this function.
+ # checks to see if inputted text is plaintext
+ result = self.lc.checkLanguage(self.text)
+ if result:
+ print("You inputted plain text!")
+ return None
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
)
# sorts each indiviudal sub-dictionary
for key, value in self.whatToChoose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.whatToChoose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.whatToChoose}"
)
self.whatToChoose = self</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>.1 in __main__ is {self.whatToChoose}"
)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# Creates and prints the probability table
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(self.whatToChoose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
|
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
e5d5f2a264ec9924ca025b17a42137adc9d22f69
|
Merge pull request #72 from Ciphey/core
|
<5>:<add> return None
<del> return None
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> # checks to see if inputted text is plaintext
<2> result = self.lc.checkLanguage(self.text)
<3> if result:
<4> print("You inputted plain text!")
<5> return None
<6> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<7> self.whatToChoose = {
<8> self.hash: {
<9> "sha1": self.probabilityDistribution[0],
<10> "md5": self.probabilityDistribution[1],
<11> "sha256": self.probabilityDistribution[2],
<12> "sha512": self.probabilityDistribution[3],
<13> },
<14> self.basic: {"caesar": self.probabilityDistribution[4]},
<15> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<16> self.encoding: {
<17> "reverse": self.probabilityDistribution[6],
<18> "base64": self.probabilityDistribution[7],
<19> "binary": self.probabilityDistribution[8],
<20> "hexadecimal": self.probabilityDistribution[9],
<21> "ascii": self.probabilityDistribution[10],
<22> "morse": self.probabilityDistribution[11],
<23> },
<24> }
<25>
<26> logger.debug(
<27> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<28> )
<29>
<30> # sorts each indiviudal sub-dictionary
<31> for key, value in self.whatToChoose.items():
<32> for k, v in value.items():
<33> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<34> if v < 0.01:
<35> self.whatToChoose[key][k] = 0.01
<36> logger.debug(
<37> f"The probability</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# Creates and prints the probability table
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(self.whatToChoose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey
produceProbTable(probTable)
one_level_of_decryption(file=None, sickomode=None)
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.lc = lc.LanguageChecker()
self.mh = mh.mathsHelper()
self.text = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
self.level = 1
self.sickomode = False
self.greppable = grep
at: ciphey.mathsHelper.mathsHelper
sortProbTable(probTable)
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
at: neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
2c2be59d71393c0dc8b5aed1eddd5207637079af
|
Added requirements.txt
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> # checks to see if inputted text is plaintext
<2> result = self.lc.checkLanguage(self.text)
<3> if result:
<4> print("You inputted plain text!")
<5> return None
<6> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<7> self.whatToChoose = {
<8> self.hash: {
<9> "sha1": self.probabilityDistribution[0],
<10> "md5": self.probabilityDistribution[1],
<11> "sha256": self.probabilityDistribution[2],
<12> "sha512": self.probabilityDistribution[3],
<13> },
<14> self.basic: {"caesar": self.probabilityDistribution[4]},
<15> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<16> self.encoding: {
<17> "reverse": self.probabilityDistribution[6],
<18> "base64": self.probabilityDistribution[7],
<19> "binary": self.probabilityDistribution[8],
<20> "hexadecimal": self.probabilityDistribution[9],
<21> "ascii": self.probabilityDistribution[10],
<22> "morse": self.probabilityDistribution[11],
<23> },
<24> }
<25>
<26> logger.debug(
<27> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<28> )
<29>
<30> # sorts each indiviudal sub-dictionary
<31> for key, value in self.whatToChoose.items():
<32> for k, v in value.items():
<33> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<34> if v < 0.01:
<35> self.whatToChoose[key][k] = 0.01
<36> logger.debug(
<37> f"The probability</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# Creates and prints the probability table
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(self.whatToChoose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey
one_level_of_decryption(file=None, sickomode=None)
at: ciphey.__main__.Ciphey.__init__
self.mh = mh.mathsHelper()
self.basic = BasicParent(self.lc)
self.encoding = EncodingParent(self.lc)
self.level = 1
self.sickomode = False
self.greppable = grep
at: ciphey.__main__.Ciphey.decrypt
self.probabilityDistribution = self.ai.predictnn(self.text)[0]
at: ciphey.mathsHelper.mathsHelper
sortProbTable(probTable)
===========changed ref 0===========
# module: ciphey.__main__
- warnings.filterwarnings("ignore")
-
===========changed ref 1===========
# module: ciphey.__main__
-
logger.add(
sys.stderr,
format="{time} {level} {message}",
filter="my_module",
level="DEBUG",
diagnose=True,
backtrace=True,
)
+ warnings.filterwarnings("ignore")
# Depening on whether ciphey is called, or ciphey/__main__
# we need different imports to deal with both cases
try:
from languageCheckerMod import LanguageChecker as lc
from neuralNetworkMod.nn import NeuralNetwork
from Decryptor.basicEncryption.basic_parent import BasicParent
from Decryptor.Hash.hashParent import HashParent
from Decryptor.Encoding.encodingParent import EncodingParent
- from Decryptor.Hash.hashParent import HashParent
except ModuleNotFoundError:
from ciphey.languageCheckerMod import LanguageChecker as lc
from ciphey.neuralNetworkMod.nn import NeuralNetwork
from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent
from ciphey.Decryptor.Hash.hashParent import HashParent
from ciphey.Decryptor.Encoding.encodingParent import EncodingParent
try:
import mathsHelper as mh
except ModuleNotFoundError:
import ciphey.mathsHelper as mh
|
|
ciphey.Decryptor.basicEncryption.viginere/Viginere.__init__
|
Modified
|
Ciphey~Ciphey
|
aedbb5b8d25e7d6f82b05ecf71b46fee1ad49e40
|
now processes candidates properly out of core
|
<0>:<add> self.LETTERS = "abcdefghijklmnopqrstuvwxyz"
<del> self.LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def __init__(self, lc):
<0> self.LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
<1> self.SILENT_MODE = True # If set to True, program doesn't print anything.
<2> self.NUM_MOST_FREQ_LETTERS = 4 # Attempt this many letters per subkey.
<3> self.MAX_KEY_LENGTH = 16 # Will not attempt keys longer than this.
<4> self.NONLETTERS_PATTERN = re.compile("[^A-Z]")
<5>
<6> self.lc = lc
<7>
|
===========unchanged ref 0===========
at: re
compile(pattern: AnyStr, flags: _FlagsType=...) -> Pattern[AnyStr]
compile(pattern: Pattern[AnyStr], flags: _FlagsType=...) -> Pattern[AnyStr]
|
ciphey.Decryptor.basicEncryption.viginere/Viginere.attemptHackWithKeyLength
|
Modified
|
Ciphey~Ciphey
|
aedbb5b8d25e7d6f82b05ecf71b46fee1ad49e40
|
now processes candidates properly out of core
|
<1>:<add> ciphertext = ciphertext.lower()
<del> ciphertextUp = ciphertext.upper()
<2>:<del> # allFreqScores is a list of mostLikelyKeyLength number of lists.
<3>:<del> # These inner lists are the freqScores lists.
<4>:<del> allFreqScores = []
<5>:<del> for nth in range(1, mostLikelyKeyLength + 1):
<6>:<del> nthLetters = self.getNthSubkeysLetters(
<7>:<del> nth, mostLikelyKeyLength, ciphertextUp
<8>:<del> )
<10>:<del> # freqScores is a list of tuples like:
<11>:<del> # [(<letter>, <Eng. Freq. match score>), ... ]
<12>:<del> # List is sorted by match score. Higher score means better match.
<13>:<del> # See the englishFreqMatchScore() comments in freqAnalysis.py.
<14>:<del> freqScores = []
<15>:<del> for possibleKey in self.LETTERS:
<16>:<del> decryptedText = self.decryptMessage(possibleKey, nthLetters)
<17>:<del> keyAndFreqMatchTuple = (
<18>:<del> possibleKey,
<19>:<del> Decryptor.basicEncryption.freqAnalysis.englishFreqMatchScore(
<20>:<del> decryptedText
<21>:<del> ),
<22>:<del> )
<23>:<del> freqScores.append(keyAndFreqMatchTuple)
<24>:<del> # Sort by match score:
<25>:<del> freqScores.sort(key=self.getItemAtIndexOne, reverse=True)
<26>:<add> # Do core work
<add> group = CipheyDists.get_charset("english")["lcase"]
<add> expected = CipheyDists.get_dist("lcase")
<add> possible_keys = core.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
<27>:<add> # Try all the feasible keys
<add> for candidate in possible_keys:
<add> nice_key = list(candidate.key)
<add> # Create a possible key from the letters in allFreqScores:
<add> if not self.SILENT_MODE:
<add> print("Attempting with key: %s" % nice_key)
<del> allFreqScores.append(freqScores[: self.NUM_MOST_FREQ_LETTERS])
<29>:<del> if not self.SILENT_MODE:
<30>:<del> for i in range(len(allFreqScores)):
<31>:<del> # Use i + 1 so the first letter is not called the "0th" letter:
<32>:<del> print("Possible letters for letter %s of the key: " % (i + 1), end="")
<33>:<del> ((bad delete))
|
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
<0> # Determine the most likely letters for each letter in the key:
<1> ciphertextUp = ciphertext.upper()
<2> # allFreqScores is a list of mostLikelyKeyLength number of lists.
<3> # These inner lists are the freqScores lists.
<4> allFreqScores = []
<5> for nth in range(1, mostLikelyKeyLength + 1):
<6> nthLetters = self.getNthSubkeysLetters(
<7> nth, mostLikelyKeyLength, ciphertextUp
<8> )
<9>
<10> # freqScores is a list of tuples like:
<11> # [(<letter>, <Eng. Freq. match score>), ... ]
<12> # List is sorted by match score. Higher score means better match.
<13> # See the englishFreqMatchScore() comments in freqAnalysis.py.
<14> freqScores = []
<15> for possibleKey in self.LETTERS:
<16> decryptedText = self.decryptMessage(possibleKey, nthLetters)
<17> keyAndFreqMatchTuple = (
<18> possibleKey,
<19> Decryptor.basicEncryption.freqAnalysis.englishFreqMatchScore(
<20> decryptedText
<21> ),
<22> )
<23> freqScores.append(keyAndFreqMatchTuple)
<24> # Sort by match score:
<25> freqScores.sort(key=self.getItemAtIndexOne, reverse=True)
<26>
<27> allFreqScores.append(freqScores[: self.NUM_MOST_FREQ_LETTERS])
<28>
<29> if not self.SILENT_MODE:
<30> for i in range(len(allFreqScores)):
<31> # Use i + 1 so the first letter is not called the "0th" letter:
<32> print("Possible letters for letter %s of the key: " % (i + 1), end="")
<33> </s>
|
===========below chunk 0===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# offset: 1
print("%s " % freqScore[0], end="")
print() # Print a newline.
# Try every combination of the most likely letters for each position
# in the key:
for indexes in itertools.product(
range(self.NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength
):
# Create a possible key from the letters in allFreqScores:
possibleKey = ""
for i in range(mostLikelyKeyLength):
possibleKey += allFreqScores[i][indexes[i]][0]
if not self.SILENT_MODE:
print("Attempting with key: %s" % (possibleKey))
decryptedText = self.decryptMessage(possibleKey, ciphertextUp)
if self.lc.checkLanguage(decryptedText):
# Set the hacked ciphertext to the original casing:
origCase = []
for i in range(len(ciphertext)):
if ciphertext[i].isupper():
origCase.append(decryptedText[i].upper())
else:
origCase.append(decryptedText[i].lower())
decryptedText = "".join(origCase)
# Check with user to see if the key has been found:
return {
"lc": self.lc,
"IsPlaintext?": True,
"Plaintext": decryptedText,
"Cipher": "Viginere",
"Extra Information": f"The key used is {possibleKey}",
}
# No English-looking decryption found, so return None:
return None
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.viginere.Viginere
kasiskiExamination(ciphertext)
at: ciphey.Decryptor.basicEncryption.viginere.Viginere.__init__
self.SILENT_MODE = True # If set to True, program doesn't print anything.
self.NUM_MOST_FREQ_LETTERS = 4 # Attempt this many letters per subkey.
self.MAX_KEY_LENGTH = 16 # Will not attempt keys longer than this.
self.lc = lc
===========changed ref 0===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def __init__(self, lc):
+ self.LETTERS = "abcdefghijklmnopqrstuvwxyz"
- self.LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.SILENT_MODE = True # If set to True, program doesn't print anything.
self.NUM_MOST_FREQ_LETTERS = 4 # Attempt this many letters per subkey.
self.MAX_KEY_LENGTH = 16 # Will not attempt keys longer than this.
self.NONLETTERS_PATTERN = re.compile("[^A-Z]")
self.lc = lc
|
ciphey.Decryptor.basicEncryption.caesar/Caesar.decrypt
|
Modified
|
Ciphey~Ciphey
|
aedbb5b8d25e7d6f82b05ecf71b46fee1ad49e40
|
now processes candidates properly out of core
|
<1>:<add> # Convert it to lower case
<add> #
<add> # TODO: handle different alphabets
<add> message = message.lower()
<del> """ Simple python program to bruteforce a caesar cipher"""
<3>:<add> # Hand it off to the core
<add> group = CipheyDists.get_charset("english")["lcase"]
<add> expected = CipheyDists.get_dist("lcase")
<add> analysis = core.analyse_string(message)
<add> possible_keys = core.caesar_crack(analysis, expected, group, True)
<del> # Example string
<4>:<del> message = message.lower()
<5>:<del> # Everything we can encrypt
<6>:<del> SYMBOLS = "abcdefghijklmnopqrstuvwxyz"
<8>:<del> for counter, key in enumerate(range(len(SYMBOLS))):
<9>:<del> # try again with each key attempt
<10>:<del> translated = ""
<11>:<del>
<12>:<del> for character in message:
<13>:<del> if character in SYMBOLS:
<14>:<del> symbolIndex = SYMBOLS.find(character)
<15>:<del> translatedIndex = symbolIndex - key
<16>:<del>
<17>:<del> # In the event of wraparound
<18>:<del> if translatedIndex < 0:
<19>:<del> translatedIndex += len(SYMBOLS)
<20>:<del>
<21>:<del> translated += SYMBOLS[translatedIndex]
<22>:<del>
<23>:<del> else:
<24>:<del> # Append the symbol without encrypting or decrypting
<25>:<del> translated += character
<26>:<del>
<27>:<del> # Output each attempt
<28>:<add> for candidate in possible_keys:
<add> translated = core.caesar_decrypt(message, candidate.key, group)
<36>:<add> "Extra Information": f"The rotation used is {candidate.key}",
<del> "Extra Information": f"The rotation used is {counter}",
<38>:<add>
|
# module: ciphey.Decryptor.basicEncryption.caesar
class Caesar:
def decrypt(self, message):
<0> logger.debug("Trying caesar Cipher")
<1> """ Simple python program to bruteforce a caesar cipher"""
<2>
<3> # Example string
<4> message = message.lower()
<5> # Everything we can encrypt
<6> SYMBOLS = "abcdefghijklmnopqrstuvwxyz"
<7>
<8> for counter, key in enumerate(range(len(SYMBOLS))):
<9> # try again with each key attempt
<10> translated = ""
<11>
<12> for character in message:
<13> if character in SYMBOLS:
<14> symbolIndex = SYMBOLS.find(character)
<15> translatedIndex = symbolIndex - key
<16>
<17> # In the event of wraparound
<18> if translatedIndex < 0:
<19> translatedIndex += len(SYMBOLS)
<20>
<21> translated += SYMBOLS[translatedIndex]
<22>
<23> else:
<24> # Append the symbol without encrypting or decrypting
<25> translated += character
<26>
<27> # Output each attempt
<28> result = self.lc.checkLanguage(translated)
<29> if result:
<30> logger.debug(f"Caesar cipher returns true {result}")
<31> return {
<32> "lc": self.lc,
<33> "IsPlaintext?": True,
<34> "Plaintext": translated,
<35> "Cipher": "Caesar",
<36> "Extra Information": f"The rotation used is {counter}",
<37> }
<38> # if none of them match English, return false!
<39> logger.debug(f"Caesar cipher returns false")
<40> return {
<41> "lc": self.lc,
<42> "IsPlaintext?": False,
<43> "Plaintext": None,
<44> "Cipher": "Caesar",
<45> "Extra Information": None,
<46> }
</s>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.caesar.Caesar
getName(self)
at: ciphey.Decryptor.basicEncryption.caesar.Caesar.__init__
self.lc = lc
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
===========changed ref 0===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def __init__(self, lc):
+ self.LETTERS = "abcdefghijklmnopqrstuvwxyz"
- self.LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.SILENT_MODE = True # If set to True, program doesn't print anything.
self.NUM_MOST_FREQ_LETTERS = 4 # Attempt this many letters per subkey.
self.MAX_KEY_LENGTH = 16 # Will not attempt keys longer than this.
self.NONLETTERS_PATTERN = re.compile("[^A-Z]")
self.lc = lc
===========changed ref 1===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# Determine the most likely letters for each letter in the key:
+ ciphertext = ciphertext.lower()
- ciphertextUp = ciphertext.upper()
- # allFreqScores is a list of mostLikelyKeyLength number of lists.
- # These inner lists are the freqScores lists.
- allFreqScores = []
- for nth in range(1, mostLikelyKeyLength + 1):
- nthLetters = self.getNthSubkeysLetters(
- nth, mostLikelyKeyLength, ciphertextUp
- )
- # freqScores is a list of tuples like:
- # [(<letter>, <Eng. Freq. match score>), ... ]
- # List is sorted by match score. Higher score means better match.
- # See the englishFreqMatchScore() comments in freqAnalysis.py.
- freqScores = []
- for possibleKey in self.LETTERS:
- decryptedText = self.decryptMessage(possibleKey, nthLetters)
- keyAndFreqMatchTuple = (
- possibleKey,
- Decryptor.basicEncryption.freqAnalysis.englishFreqMatchScore(
- decryptedText
- ),
- )
- freqScores.append(keyAndFreqMatchTuple)
- # Sort by match score:
- freqScores.sort(key=self.getItemAtIndexOne, reverse=True)
+ # Do core work
+ group = CipheyDists.get_charset("english")["lcase"]
+ expected = CipheyDists.get_dist("lcase")
+ possible_keys = core.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
+ # Try all the feasible keys
+ for candidate in possible_keys:
</s>
===========changed ref 2===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# offset: 1
<s>elyKeyLength)
+ # Try all the feasible keys
+ for candidate in possible_keys:
+ nice_key = list(candidate.key)
+ # Create a possible key from the letters in allFreqScores:
+ if not self.SILENT_MODE:
+ print("Attempting with key: %s" % nice_key)
- allFreqScores.append(freqScores[: self.NUM_MOST_FREQ_LETTERS])
- if not self.SILENT_MODE:
- for i in range(len(allFreqScores)):
- # Use i + 1 so the first letter is not called the "0th" letter:
- print("Possible letters for letter %s of the key: " % (i + 1), end="")
- for freqScore in allFreqScores[i]:
- print("%s " % freqScore[0], end="")
- print() # Print a newline.
-
- # Try every combination of the most likely letters for each position
- # in the key:
- for indexes in itertools.product(
- range(self.NUM_MOST_FREQ_LETTERS), repeat=mostLikelyKeyLength
- ):
- # Create a possible key from the letters in allFreqScores:
- possibleKey = ""
- for i in range(mostLikelyKeyLength):
- possibleKey += allFreqScores[i][indexes[i]][0]
-
- if not self.SILENT_MODE:
- print("Attempting with key: %s" % (possibleKey))
-
- decryptedText = self.decrypt</s>
===========changed ref 3===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# offset: 2
<s>possibleKey, ciphertextUp)
+ decryptedText = core.vigerene_decrypt(ciphertext, candidate.key, group)
if self.lc.checkLanguage(decryptedText):
# Set the hacked ciphertext to the original casing:
origCase = []
for i in range(len(ciphertext)):
if ciphertext[i].isupper():
origCase.append(decryptedText[i].upper())
else:
origCase.append(decryptedText[i].lower())
decryptedText = "".join(origCase)
# Check with user to see if the key has been found:
return {
"lc": self.lc,
"IsPlaintext?": True,
"Plaintext": decryptedText,
"Cipher": "Viginere",
+ "Extra Information": f"The key used is {nice_key}",
- "Extra Information": f"The key used is {possibleKey}",
}
# No English-looking decryption found, so return None:
return None
|
ciphey.Decryptor.basicEncryption.viginere/Viginere.attemptHackWithKeyLength
|
Modified
|
Ciphey~Ciphey
|
33fa71f23ec2bbf792fa8044554929ad30543868
|
Integrated latest cipheycore
|
<6>:<add> possible_keys = cipheycore.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
<del> possible_keys = core.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
<15>:<add> decryptedText = cipheycore.vigerene_decrypt(ciphertext, candidate.key, group)
<del> decryptedText = core.vigerene_decrypt(ciphertext, candidate.key, group)
|
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
<0> # Determine the most likely letters for each letter in the key:
<1> ciphertext = ciphertext.lower()
<2>
<3> # Do core work
<4> group = CipheyDists.get_charset("english")["lcase"]
<5> expected = CipheyDists.get_dist("lcase")
<6> possible_keys = core.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
<7>
<8> # Try all the feasible keys
<9> for candidate in possible_keys:
<10> nice_key = list(candidate.key)
<11> # Create a possible key from the letters in allFreqScores:
<12> if not self.SILENT_MODE:
<13> print("Attempting with key: %s" % nice_key)
<14>
<15> decryptedText = core.vigerene_decrypt(ciphertext, candidate.key, group)
<16>
<17> if self.lc.checkLanguage(decryptedText):
<18> # Set the hacked ciphertext to the original casing:
<19> origCase = []
<20> for i in range(len(ciphertext)):
<21> if ciphertext[i].isupper():
<22> origCase.append(decryptedText[i].upper())
<23> else:
<24> origCase.append(decryptedText[i].lower())
<25> decryptedText = "".join(origCase)
<26>
<27> # Check with user to see if the key has been found:
<28> return {
<29> "lc": self.lc,
<30> "IsPlaintext?": True,
<31> "Plaintext": decryptedText,
<32> "Cipher": "Viginere",
<33> "Extra Information": f"The key used is {nice_key}",
<34> }
<35>
<36> # No English-look</s>
|
===========below chunk 0===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# offset: 1
return None
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.viginere.Viginere.__init__
self.SILENT_MODE = True # If set to True, program doesn't print anything.
self.lc = lc
at: ciphey.Decryptor.basicEncryption.viginere.Viginere.getNthSubkeysLetters
letters = []
|
ciphey.Decryptor.basicEncryption.caesar/Caesar.decrypt
|
Modified
|
Ciphey~Ciphey
|
33fa71f23ec2bbf792fa8044554929ad30543868
|
Integrated latest cipheycore
|
<7>:<add> group = cipheydists.get_charset("english")["lcase"]
<del> group = CipheyDists.get_charset("english")["lcase"]
<8>:<add> expected = cipheydists.get_dist("lcase")
<del> expected = CipheyDists.get_dist("lcase")
<9>:<add> analysis = cipheycore.analyse_string(message)
<del> analysis = core.analyse_string(message)
<10>:<add> possible_keys = cipheycore.caesar_crack(analysis, expected, group)
<del> possible_keys = core.caesar_crack(analysis, expected, group, True)
<11>:<add> n_candidates = len(possible_keys)
<add> logger.debug(f"Caesar cipher core heuristic returned {n_candidates} candidates")
<13>:<add> translated = cipheycore.caesar_decrypt(message, candidate.key, group)
<del> translated = core.caesar_decrypt(message, candidate.key, group)
|
# module: ciphey.Decryptor.basicEncryption.caesar
class Caesar:
def decrypt(self, message):
<0> logger.debug("Trying caesar Cipher")
<1> # Convert it to lower case
<2> #
<3> # TODO: handle different alphabets
<4> message = message.lower()
<5>
<6> # Hand it off to the core
<7> group = CipheyDists.get_charset("english")["lcase"]
<8> expected = CipheyDists.get_dist("lcase")
<9> analysis = core.analyse_string(message)
<10> possible_keys = core.caesar_crack(analysis, expected, group, True)
<11>
<12> for candidate in possible_keys:
<13> translated = core.caesar_decrypt(message, candidate.key, group)
<14> result = self.lc.checkLanguage(translated)
<15> if result:
<16> logger.debug(f"Caesar cipher returns true {result}")
<17> return {
<18> "lc": self.lc,
<19> "IsPlaintext?": True,
<20> "Plaintext": translated,
<21> "Cipher": "Caesar",
<22> "Extra Information": f"The rotation used is {candidate.key}",
<23> }
<24>
<25> # if none of them match English, return false!
<26> logger.debug(f"Caesar cipher returns false")
<27> return {
<28> "lc": self.lc,
<29> "IsPlaintext?": False,
<30> "Plaintext": None,
<31> "Cipher": "Caesar",
<32> "Extra Information": None,
<33> }
<34>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.caesar.Caesar.__init__
self.lc = lc
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
===========changed ref 0===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# Determine the most likely letters for each letter in the key:
ciphertext = ciphertext.lower()
# Do core work
group = CipheyDists.get_charset("english")["lcase"]
expected = CipheyDists.get_dist("lcase")
+ possible_keys = cipheycore.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
- possible_keys = core.vigerene_crack(ciphertext, expected, group, mostLikelyKeyLength)
# Try all the feasible keys
for candidate in possible_keys:
nice_key = list(candidate.key)
# Create a possible key from the letters in allFreqScores:
if not self.SILENT_MODE:
print("Attempting with key: %s" % nice_key)
+ decryptedText = cipheycore.vigerene_decrypt(ciphertext, candidate.key, group)
- decryptedText = core.vigerene_decrypt(ciphertext, candidate.key, group)
if self.lc.checkLanguage(decryptedText):
# Set the hacked ciphertext to the original casing:
origCase = []
for i in range(len(ciphertext)):
if ciphertext[i].isupper():
origCase.append(decryptedText[i].upper())
else:
origCase.append(decryptedText[i].lower())
decryptedText = "".join(origCase)
# Check with user to see if the key has been found:
return {
"lc": self.lc,
"IsPlaintext?": True,
"Plaintext": decryptedText,
"Cipher": "Viginere",
"Extra Information":</s>
===========changed ref 1===========
# module: ciphey.Decryptor.basicEncryption.viginere
class Viginere:
def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength):
# offset: 1
<s>,
"Plaintext": decryptedText,
"Cipher": "Viginere",
"Extra Information": f"The key used is {nice_key}",
}
# No English-looking decryption found, so return None:
return None
|
ciphey.Decryptor.basicEncryption.basic_parent/BasicParent.decrypt
|
Modified
|
Ciphey~Ciphey
|
568d3b937dd1a8783e95c4367a6120ff0d3ea813
|
Merge pull request #75 from Ciphey/core
|
<22>:<add> """
<28>:<add> }
<del> }"""
|
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
<0> self.text = text
<1> from multiprocessing.dummy import Pool as ThreadPool
<2>
<3> pool = ThreadPool(4)
<4> answers = pool.map(self.callDecrypt, self.list_of_objects)
<5>
<6> """for item in self.list_of_objects:
<7> result = item.decrypt(text)
<8> answers.append(result)"""
<9> for answer in answers:
<10> # adds the LC objects together
<11> self.lc = self.lc + answer["lc"]
<12> if answer["IsPlaintext?"]:
<13> return answer
<14>
<15> # so viginere runs ages
<16> # and you cant kill threads in a pool
<17> # so i just run it last lol]
<18> """
<19> result = self.callDecrypt(self.viginere)
<20> if result["IsPlaintext?"]:
<21> return result
<22> return {
<23> "lc": self.lc,
<24> "IsPlaintext?": False,
<25> "Plaintext": None,
<26> "Cipher": None,
<27> "Extra Information": None,
<28> }"""
<29>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent
callDecrypt(obj)
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent.__init__
self.lc = lc
self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans]
at: multiprocessing.dummy
Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any
|
ciphey.__main__/Ciphey.one_level_of_decryption
|
Modified
|
Ciphey~Ciphey
|
568d3b937dd1a8783e95c4367a6120ff0d3ea813
|
Merge pull request #75 from Ciphey/core
|
<6>:<del> with alive_bar() as bar:
<7>:<add> logger.debug("__main__ is running with progress bar")
<del> logger.debug("__main__ is running with progress bar")
<8>:<add> self.decryptNormal()
<del> self.decryptNormal(bar)
|
# module: ciphey.__main__
class Ciphey:
def one_level_of_decryption(self, file=None, sickomode=None):
<0> # Calls one level of decryption
<1> # mainly used to control the progress bar
<2> if self.greppable:
<3> logger.debug("__main__ is running as greppable")
<4> self.decryptNormal()
<5> else:
<6> with alive_bar() as bar:
<7> logger.debug("__main__ is running with progress bar")
<8> self.decryptNormal(bar)
<9>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.greppable = grep
===========changed ref 0===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
self.text = text
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
answers = pool.map(self.callDecrypt, self.list_of_objects)
"""for item in self.list_of_objects:
result = item.decrypt(text)
answers.append(result)"""
for answer in answers:
# adds the LC objects together
self.lc = self.lc + answer["lc"]
if answer["IsPlaintext?"]:
return answer
# so viginere runs ages
# and you cant kill threads in a pool
# so i just run it last lol]
"""
result = self.callDecrypt(self.viginere)
if result["IsPlaintext?"]:
return result
+ """
return {
"lc": self.lc,
"IsPlaintext?": False,
"Plaintext": None,
"Cipher": None,
"Extra Information": None,
+ }
- }"""
|
ciphey.__main__/Ciphey.decryptNormal
|
Modified
|
Ciphey~Ciphey
|
568d3b937dd1a8783e95c4367a6120ff0d3ea813
|
Merge pull request #75 from Ciphey/core
|
<4>:<add> logger.debug(f"Running {key}")
<5>:<add> try:
<add> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<del> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<6>:<add> except TypeError:
<add> logger.debug(f"********************************The key is {key}")
<add> exit(1)
<add> try:
<add> logger.debug(
<del> logger.debug(
<7>:<add> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<del> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<8>:<add> )
<del> )
<9>:<add> except TypeError as e:
<add> logger.debug(f"**********The key is {key}")
<add> exit(1)
<del>
<23>:<del> if not self.greppable:
<24>:<del> bar()
|
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
<0> for key, val in self.whatToChoose.items():
<1> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
<2> if not isinstance(key, str):
<3> key.setProbTable(val)
<4> ret = key.decrypt(self.text)
<5> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<6> logger.debug(
<7> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<8> )
<9>
<10> if ret["IsPlaintext?"]:
<11> print(ret["Plaintext"])
<12> if self.cipher:
<13> if ret["Extra Information"] != None:
<14> print(
<15> "The cipher used is",
<16> ret["Cipher"] + ".",
<17> ret["Extra Information"] + ".",
<18> )
<19> else:
<20> print("The cipher used is " + ret["Cipher"] + ".")
<21> return ret
<22>
<23> if not self.greppable:
<24> bar()
<25> logger.debug("No encryption found")
<26> print(
<27> """No encryption found. Here are some tips to help crack the cipher:
<28> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
<29> * If the probability table says 'Caesar Cipher' then it is a normal encryption that Ciphey cannot decrypt yet.
<30> * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, and then HashCat to crack the hash.
<31> * The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
# offset: 1
)
===========unchanged ref 0===========
at: Decryptor.basicEncryption.basic_parent.BasicParent
decrypt(text)
setProbTable(prob)
at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent
setProbTable(table)
decrypt(text)
at: ciphey.Decryptor.Hash.hashParent.HashParent
decrypt(text)
setProbTable(val)
at: ciphey.__main__.Ciphey.__init__
self.text = text
self.cipher = cipher
at: ciphey.__main__.Ciphey.decrypt
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
self.whatToChoose = {
self.hash: {
"sha1": self.probabilityDistribution[0],
"md5": self.probabilityDistribution[1],
"sha256": self.probabilityDistribution[2],
"sha512": self.probabilityDistribution[3],
},
self.basic: {"caesar": self.probabilityDistribution[4]},
"plaintext": {"plaintext": self.probabilityDistribution[5]},
self.encoding: {
"reverse": self.probabilityDistribution[6],
"base64": self.probabilityDistribution[7],
"binary": self.probabilityDistribution[8],
"hexadecimal": self.probabilityDistribution[9],
"ascii": self.probabilityDistribution[10],
"morse": self.probabilityDistribution[11],
},
}
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def one_level_of_decryption(self, file=None, sickomode=None):
# Calls one level of decryption
# mainly used to control the progress bar
if self.greppable:
logger.debug("__main__ is running as greppable")
self.decryptNormal()
else:
- with alive_bar() as bar:
+ logger.debug("__main__ is running with progress bar")
- logger.debug("__main__ is running with progress bar")
+ self.decryptNormal()
- self.decryptNormal(bar)
===========changed ref 1===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
self.text = text
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
answers = pool.map(self.callDecrypt, self.list_of_objects)
"""for item in self.list_of_objects:
result = item.decrypt(text)
answers.append(result)"""
for answer in answers:
# adds the LC objects together
self.lc = self.lc + answer["lc"]
if answer["IsPlaintext?"]:
return answer
# so viginere runs ages
# and you cant kill threads in a pool
# so i just run it last lol]
"""
result = self.callDecrypt(self.viginere)
if result["IsPlaintext?"]:
return result
+ """
return {
"lc": self.lc,
"IsPlaintext?": False,
"Plaintext": None,
"Cipher": None,
"Extra Information": None,
+ }
- }"""
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
568d3b937dd1a8783e95c4367a6120ff0d3ea813
|
Merge pull request #75 from Ciphey/core
|
# module: ciphey.__main__
def main():
<0>
<1> parser = argparse.ArgumentParser(
<2> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<3> Examples:
<4> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<5> """
<6> )
<7> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<8> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<9> parser.add_argument(
<10> "-g",
<11> "--greppable",
<12> help="Only output the answer, no progress bars or information. Useful for grep",
<13> action="store_true",
<14> required=False,
<15> )
<16> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<17> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<18> parser.add_argument(
<19> "-c",
<20> "--printcipher",
<21> help="Do you want information on the cipher used?",
<22> action="store_true",
<23> required=False,
<24> )
<25> # fake argument to stop argparser complaining about no arguments
<26> # allows sys.argv to be used
<27> parser.add_argument("-m", action="store_false", default=True, required=False)
<28>
<29> parser.add_argument(
<30> "-d",
<31> "--debug",
<32> help="Activates debug mode",
<33> required=False,
<34> action="store_true",
<35> )
<36> parser.add_argument("rest", nargs=argparse.REMAINDER)</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def main():
# offset: 1
args = vars(parser.parse_args())
if args["printcipher"]:
cipher = True
else:
cipher = False
if args["greppable"]:
greppable = True
else:
greppable = False
if args["debug"]:
debug = True
else:
debug = False
text = None
# the below text does:
# if -t is supplied, use that
# if ciphey is called like:
# ciphey 'encrypted text' use that
# else if data is piped like:
# echo 'hello' | ciphey use that
# if no data is supplied, no arguments supplied.
if args["text"]:
text = args["text"]
if args["text"] == None and len(sys.argv) > 1:
text = args["rest"][0]
print(f"text is {text}")
if not sys.stdin.isatty():
text = str(sys.stdin.read())
if len(sys.argv) == 1 and text == None:
print("No arguments were supplied. Look at the help menu with -h or --help")
if text != None:
cipherObj = Ciphey(text, greppable, cipher, debug)
cipherObj.decrypt()
===========unchanged ref 0===========
at: argparse
REMAINDER = '...'
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: sys
argv: List[str]
stdin: TextIO
at: typing.IO
__slots__ = ()
isatty() -> bool
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def one_level_of_decryption(self, file=None, sickomode=None):
# Calls one level of decryption
# mainly used to control the progress bar
if self.greppable:
logger.debug("__main__ is running as greppable")
self.decryptNormal()
else:
- with alive_bar() as bar:
+ logger.debug("__main__ is running with progress bar")
- logger.debug("__main__ is running with progress bar")
+ self.decryptNormal()
- self.decryptNormal(bar)
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
for key, val in self.whatToChoose.items():
# https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
if not isinstance(key, str):
key.setProbTable(val)
+ logger.debug(f"Running {key}")
ret = key.decrypt(self.text)
+ try:
+ logger.debug(f"Decrypt normal in __main__ ret is {ret}")
- logger.debug(f"Decrypt normal in __main__ ret is {ret}")
+ except TypeError:
+ logger.debug(f"********************************The key is {key}")
+ exit(1)
+ try:
+ logger.debug(
- logger.debug(
+ f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
- f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
+ )
- )
+ except TypeError as e:
+ logger.debug(f"**********The key is {key}")
+ exit(1)
-
if ret["IsPlaintext?"]:
print(ret["Plaintext"])
if self.cipher:
if ret["Extra Information"] != None:
print(
"The cipher used is",
ret["Cipher"] + ".",
ret["Extra Information"] + ".",
)
else:
print("The cipher used is " + ret["Cipher"] + ".")
return ret
- if not self.greppable:
- bar()
logger.debug("No encryption found")
print(
"""No encryption found. Here are some tips to help</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decryptNormal(self, bar=None):
# offset: 1
<s>
logger.debug("No encryption found")
print(
"""No encryption found. Here are some tips to help crack the cipher:
* Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
* If the probability table says 'Caesar Cipher' then it is a normal encryption that Ciphey cannot decrypt yet.
* If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, and then HashCat to crack the hash.
* The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log file of all attempted decryptions and manually search it."""
)
|
|
ciphey.SimpleClassifier.encoding/HexClassifier.name
|
Modified
|
Ciphey~Ciphey
|
69dce1c862381717e9262b99d606bdba75e43b74
|
Added binary classifier
|
<0>:<add> return "base16"
<del> return "hex"
|
# module: ciphey.SimpleClassifier.encoding
class HexClassifier(SimpleClassifier.base.Classifier):
+ def name(): return "base16"
- def name(): return "hex"
<0> return "hex"
<1>
|
===========unchanged ref 0===========
at: SimpleClassifier.base.Classifier
name() -> str
|
ciphey.SimpleClassifier/filterOut
|
Modified
|
Ciphey~Ciphey
|
69dce1c862381717e9262b99d606bdba75e43b74
|
Added binary classifier
|
<1>:<add> for c in [HexClassifier, Base64Classifier, BinaryClassifier]:
<del> for c in [HexClassifier, Base64Classifier]:
|
# module: ciphey.SimpleClassifier
def filterOut(data:str) -> set:
<0> ret = set()
<1> for c in [HexClassifier, Base64Classifier]:
<2> if c.isImpossible(data):
<3> ret.add(c.name())
<4> return ret
<5>
|
===========unchanged ref 0===========
at: SimpleClassifier.encoding
HexClassifier()
Base64Classifier()
BinaryClassifier()
at: SimpleClassifier.encoding.Base64Classifier
name()
isImpossible(data: str)
at: SimpleClassifier.encoding.BinaryClassifier
name()
isImpossible(data: str)
at: SimpleClassifier.encoding.HexClassifier
name()
isImpossible(data: str)
===========changed ref 0===========
# module: ciphey.SimpleClassifier.encoding
+ class BinaryClassifier(SimpleClassifier.base.Classifier):
+ def name(): return "base2"
+ return "base2"
+
===========changed ref 1===========
# module: ciphey.SimpleClassifier.encoding
class HexClassifier(SimpleClassifier.base.Classifier):
+ def name(): return "base16"
- def name(): return "hex"
+ return "base16"
- return "hex"
===========changed ref 2===========
# module: ciphey.SimpleClassifier.encoding
+ class BinaryClassifier(SimpleClassifier.base.Classifier):
+ def isImpossible(data: str):
+ return not checkCharsIn(data, set(0,1))
+
|
ciphey.SimpleClassifier/filterOut
|
Modified
|
Ciphey~Ciphey
|
3ba88a7cd4193dfc4da85b5b1c5d50a817101e14
|
That should do it for the simple classifier
|
<0>:<add> ret = filterResults()
<add> ret.lengths.add(len(data))
<add> # First, gather the encodings, so that we can get the lengths
<add> for encoding in all_encoding_classifiers:
<add> res = encoding.classify(data)
<add> if res:
<add> ret.lengths |= res
<add> else:
<add> ret.failed_encodings.add(encoding.name())
<add>
<add> # Now we can iterate over the rest
<add> for hash in all_hash_classifiers:
<del> ret = set()
<1>:<del> for c in [HexClassifier, Base64Classifier, BinaryClassifier]:
<2>:<add> if hash.isImpossible(data, ret.lengths):
<del> if c.isImpossible(data):
<3>:<add> ret.failed_hashes.add(hash.name())
<add>
<del> ret.add(c.name())
|
# module: ciphey.SimpleClassifier
+ def filterOut(data:str) -> filterResults:
- def filterOut(data:str) -> set:
<0> ret = set()
<1> for c in [HexClassifier, Base64Classifier, BinaryClassifier]:
<2> if c.isImpossible(data):
<3> ret.add(c.name())
<4> return ret
<5>
|
===========changed ref 0===========
# module: ciphey.SimpleClassifier.base
+ class LengthInformedClassifier(ClassifierBase):
+ def isImpossible(data: str, lengths: set) -> bool: pass
+ pass
+
===========changed ref 1===========
# module: ciphey.SimpleClassifier.base
+ class EncodingClassifier(ClassifierBase):
+ def classify(data: str) -> set: pass
+ pass
+
===========changed ref 2===========
# module: ciphey.SimpleClassifier.base
+ class ClassifierBase():
+ def name() -> str: pass
+ pass
+
===========changed ref 3===========
# module: ciphey.SimpleClassifier.base
+ class ClassifierBase():
+ def name() -> str: pass
+ pass
+
===========changed ref 4===========
+ # module: ciphey.SimpleClassifier.hashes
+ class Md5Classifier(LengthInformedClassifier):
+ def name(): return "MD5"
+ return "MD5"
+
===========changed ref 5===========
# module: ciphey.SimpleClassifier.encoding
+ class DecimalClassifier(SimpleClassifier.base.Classifier):
+ def name(): return "base10"
+ return "base10"
+
===========changed ref 6===========
+ # module: ciphey.SimpleClassifier.hashes
+ class Sha256Classfier(LengthInformedClassifier):
+ def isImpossible(data: str, lengths:set):
+ return 32 not in lengths
+
===========changed ref 7===========
+ # module: ciphey.SimpleClassifier.hashes
+ class Md5Classifier(LengthInformedClassifier):
+ def isImpossible(data: str, lengths: set):
+ return 16 not in lengths
+
===========changed ref 8===========
+ # module: ciphey.SimpleClassifier.hashes
+ class Sha256Classfier(LengthInformedClassifier):
+ def name(): return "SHA2-256"
+ return "SHA2-256"
+
===========changed ref 9===========
+ # module: ciphey.SimpleClassifier.hashes
+ def checkCharsIn(data : str, charset : set):
+ return all(char in charset for char in data)
+
===========changed ref 10===========
# module: ciphey.SimpleClassifier.encoding
class BinaryClassifier(SimpleClassifier.base.Classifier):
- def isImpossible(data: str):
- return not checkCharsIn(data, set(0,1))
-
===========changed ref 11===========
# module: ciphey.SimpleClassifier.encoding
+ class DecimalClassifier(SimpleClassifier.base.Classifier):
+ def classify(data: str):
+ try: return {-(-int(data).bit_length() // 8)}
+ except: return set()
+
===========changed ref 12===========
# module: ciphey.SimpleClassifier.encoding
class Base64Classifier(SimpleClassifier.base.Classifier):
- def isImpossible(data: str):
- return not checkCharsIn(data, set(cipheydists.get_charset("encodings")["base64"]))
-
===========changed ref 13===========
+ # module: ciphey.SimpleClassifier.hashes
+ all_hash_classifiers = [Md5Classifier, Sha256Classfier]
+ all_hashes = [i.name() for i in all_hash_classifiers]
+
===========changed ref 14===========
# module: ciphey.SimpleClassifier.encoding
+ all_encoding_classifiers = [HexClassifier, Base64Classifier, BinaryClassifier, DecimalClassifier]
+ all_encodings = [i.name() for i in all_encoding_classifiers]
-
===========changed ref 15===========
# module: ciphey.SimpleClassifier.encoding
class Base64Classifier(SimpleClassifier.base.Classifier):
+ def classify(data: str):
+ if not checkCharsIn(data, set(cipheydists.get_charset("encodings")["base64"])):
+ return set()
+ return {-(-len(data) // 3) * 4}
+
===========changed ref 16===========
# module: ciphey.SimpleClassifier.encoding
class BinaryClassifier(SimpleClassifier.base.Classifier):
+ def classify(data: str):
+ if (len(data) >= 2 and data[0] == '0' and data[1] == 'b'):
+ data = data[2:]
+ if not checkCharsIn(data, {0,1}):
+ return set()
+ return {-(-len(data) // 2)}
+
===========changed ref 17===========
# module: ciphey.SimpleClassifier.encoding
+ class HexClassifier(SimpleClassifier.base.EncodingClassifier):
- class HexClassifier(SimpleClassifier.base.Classifier):
- def isImpossible(data: str):
- # Skip 0x
- if (len(data) >= 2 and data[0] == '0' and (data[1] == 'x' or data[1] == 'X')):
- data = data[2:]
- return not checkCharsIn(data, set(cipheydists.get_charset("encodings")["hex"]))
-
===========changed ref 18===========
# module: ciphey.SimpleClassifier.encoding
+ class HexClassifier(SimpleClassifier.base.EncodingClassifier):
- class HexClassifier(SimpleClassifier.base.Classifier):
+ def classify(data: str):
+ # Skip 0x
+ if (len(data) >= 2 and data[0] == '0' and (data[1] == 'x' or data[1] == 'X')):
+ data = data[2:]
+ if not checkCharsIn(data, set(cipheydists.get_charset("encodings")["hex"])):
+ return set()
+ return {-(-len(data) // 2)}
+
|
ciphey.Decryptor.basicEncryption.basic_parent/BasicParent.__init__
|
Modified
|
Ciphey~Ciphey
|
6bd9237cea6e5b1525a49ed2e81544f932376199
|
Integrated vigenere
|
<3>:<add> self.vigenere = vi.Vigenere(self.lc)
<del> self.viginere = vi.Viginere(self.lc)
|
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def __init__(self, lc):
<0> self.lc = lc
<1> self.caesar = ca.Caesar(self.lc)
<2> self.reverse = re.Reverse(self.lc)
<3> self.viginere = vi.Viginere(self.lc)
<4> self.pig = pi.PigLatin(self.lc)
<5> self.trans = tr.Transposition(self.lc)
<6>
<7> self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans]
<8>
|
===========unchanged ref 0===========
at: Decryptor.basicEncryption.transposition
Transposition(lc)
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent.decrypt
self.lc = self.lc + answer["lc"]
at: ciphey.Decryptor.basicEncryption.caesar
Caesar(lc)
at: ciphey.Decryptor.basicEncryption.pigLatin
PigLatin(lc)
at: ciphey.Decryptor.basicEncryption.reverse
Reverse(lc)
at: ciphey.Decryptor.basicEncryption.vigenere
Vigenere(lc)
===========changed ref 0===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def getItemAtIndexOne(self, items):
+ return items[1]
+
===========changed ref 1===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def getName(self):
+ return "Viginere"
+
===========changed ref 2===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def decryptMessage(self, key, message):
+ return self.translateMessage(key, message, "decrypt")
+
===========changed ref 3===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+ try:
+ import Decryptor.basicEncryption.freqAnalysis
+ except ModuleNotFoundError:
+ import ciphey.Decryptor.basicEncryption.freqAnalysis
+
===========changed ref 4===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ # If vigenereHacker.py is run (instead of imported as a module) call
+ # the main() function.
+ if __name__ == "__main__":
+ v = Viginere()
+ v.main()
+
===========changed ref 5===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def decrypt(self, text):
+ result = self.hackVigenere(text)
+ if result is None:
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": False,
+ "Plaintext": None,
+ "Cipher": "Viginere",
+ "Extra Information": None,
+ }
+
+ return result
+
===========changed ref 6===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
"""
██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗
██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝
██║ ██║██████╔╝███████║█████╗ ╚████╔╝
██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝
╚██████╗█�</s>
===========changed ref 7===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
# offset: 1
<s>
╚██████╗██║██║ ██║ ██║███████╗ ██║
© Brandon Skerritt
https://github.com/brandonskerritt/ciphey
"""
try:
import Decryptor.basicEncryption.caesar as ca
import Decryptor.basicEncryption.reverse as re
+ import Decryptor.basicEncryption.vigenere as vi
- import Decryptor.basicEncryption.viginere as vi
import Decryptor.basicEncryption.pigLatin as pi
import Decryptor.basicEncryption.transposition as tr
except ModuleNotFoundError:
import ciphey.Decryptor.basicEncryption.caesar as ca
import ciphey.Decryptor.basicEncryption.reverse as re
+ import ciphey.Decryptor.basicEncryption.vigenere as vi
- import ciphey.Decryptor.basicEncryption.viginere as vi
import ciphey.Decryptor.basicEncryption.pigLatin as pi
import ciphey.Decryptor.basicEncryption.transposition as tr
"""
So I want to assign the prob distribution to objects
so it makes sense to do this?
list of objects
for each item in the prob distribution
replace that with the appropriate object in the list?
So each object has a getName func that returns the name as a str
new_prob_dict = {}
for key, val in self.prob:
for obj in list:
if obj.getName() ==</s>
===========changed ref 8===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
# offset: 2
<s>
new_prob_dict[obj] = val
But I don't need to do all this, do I?
The dict comes in already sorted.
So why do I need the probability values if it's sorted?
It'd be easier if I make a list in the same order as the dict?
sooo
list_objs = [caeser, etc]
counter = 0
for key, val in self.prob:
for listCounter, item in enumerate(list_objs):
if item.getName() == key:
# moves the item
list_objs.insert(counter, list_objs.pop(listCounter))
counter = counter + 1
Eventually we get a sorted list of obj
"""
|
ciphey.Decryptor.basicEncryption.basic_parent/BasicParent.decrypt
|
Modified
|
Ciphey~Ciphey
|
6bd9237cea6e5b1525a49ed2e81544f932376199
|
Integrated vigenere
|
<15>:<add> # so vigenere runs ages
<del> # so viginere runs ages
<18>:<add> #
<del> """
<19>:<add> # Not anymore! #basedcore
<add>
<add> result = self.callDecrypt(self.vigenere)
<del> result = self.callDecrypt(self.viginere)
<22>:<add>
<del> """
|
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
<0> self.text = text
<1> from multiprocessing.dummy import Pool as ThreadPool
<2>
<3> pool = ThreadPool(4)
<4> answers = pool.map(self.callDecrypt, self.list_of_objects)
<5>
<6> """for item in self.list_of_objects:
<7> result = item.decrypt(text)
<8> answers.append(result)"""
<9> for answer in answers:
<10> # adds the LC objects together
<11> self.lc = self.lc + answer["lc"]
<12> if answer["IsPlaintext?"]:
<13> return answer
<14>
<15> # so viginere runs ages
<16> # and you cant kill threads in a pool
<17> # so i just run it last lol]
<18> """
<19> result = self.callDecrypt(self.viginere)
<20> if result["IsPlaintext?"]:
<21> return result
<22> """
<23> return {
<24> "lc": self.lc,
<25> "IsPlaintext?": False,
<26> "Plaintext": None,
<27> "Cipher": None,
<28> "Extra Information": None,
<29> }
<30>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent
callDecrypt(obj)
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent.__init__
self.lc = lc
self.vigenere = vi.Vigenere(self.lc)
self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans]
at: multiprocessing.dummy
Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any
===========changed ref 0===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def __init__(self, lc):
self.lc = lc
self.caesar = ca.Caesar(self.lc)
self.reverse = re.Reverse(self.lc)
+ self.vigenere = vi.Vigenere(self.lc)
- self.viginere = vi.Viginere(self.lc)
self.pig = pi.PigLatin(self.lc)
self.trans = tr.Transposition(self.lc)
self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans]
===========changed ref 1===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def getItemAtIndexOne(self, items):
+ return items[1]
+
===========changed ref 2===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def getName(self):
+ return "Viginere"
+
===========changed ref 3===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def decryptMessage(self, key, message):
+ return self.translateMessage(key, message, "decrypt")
+
===========changed ref 4===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+ try:
+ import Decryptor.basicEncryption.freqAnalysis
+ except ModuleNotFoundError:
+ import ciphey.Decryptor.basicEncryption.freqAnalysis
+
===========changed ref 5===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ # If vigenereHacker.py is run (instead of imported as a module) call
+ # the main() function.
+ if __name__ == "__main__":
+ v = Viginere()
+ v.main()
+
===========changed ref 6===========
+ # module: ciphey.Decryptor.basicEncryption.vigenere
+
+
+ class Vigenere:
+
+ def decrypt(self, text):
+ result = self.hackVigenere(text)
+ if result is None:
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": False,
+ "Plaintext": None,
+ "Cipher": "Viginere",
+ "Extra Information": None,
+ }
+
+ return result
+
===========changed ref 7===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
"""
██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗
██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝
██║ ██║██████╔╝███████║█████╗ ╚████╔╝
██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝
╚██████╗█�</s>
===========changed ref 8===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
# offset: 1
<s>
╚██████╗██║██║ ██║ ██║███████╗ ██║
© Brandon Skerritt
https://github.com/brandonskerritt/ciphey
"""
try:
import Decryptor.basicEncryption.caesar as ca
import Decryptor.basicEncryption.reverse as re
+ import Decryptor.basicEncryption.vigenere as vi
- import Decryptor.basicEncryption.viginere as vi
import Decryptor.basicEncryption.pigLatin as pi
import Decryptor.basicEncryption.transposition as tr
except ModuleNotFoundError:
import ciphey.Decryptor.basicEncryption.caesar as ca
import ciphey.Decryptor.basicEncryption.reverse as re
+ import ciphey.Decryptor.basicEncryption.vigenere as vi
- import ciphey.Decryptor.basicEncryption.viginere as vi
import ciphey.Decryptor.basicEncryption.pigLatin as pi
import ciphey.Decryptor.basicEncryption.transposition as tr
"""
So I want to assign the prob distribution to objects
so it makes sense to do this?
list of objects
for each item in the prob distribution
replace that with the appropriate object in the list?
So each object has a getName func that returns the name as a str
new_prob_dict = {}
for key, val in self.prob:
for obj in list:
if obj.getName() ==</s>
|
ciphey.Decryptor.Encoding.base64/Base64.decrypt
|
Modified
|
Ciphey~Ciphey
|
4937464657ada553c2905804b6a4aec88501ea1e
|
Fixed bug where Base64.py did not use languageChecker
|
<17>:<add> if self.lc.checkLanguage(result) and result != "None":
<del> if self.lc.checkLanguage(result):
<34>:<add> if self.lc.checkLanguage(result) and result != "None":
<del> if self.lc.checkLanguage(result):
|
# module: ciphey.Decryptor.Encoding.base64
class Base64:
def decrypt(self, text):
<0> logger.debug("Attempting base decoding")
<1> result = "None"
<2> ciph = "None"
<3>
<4> # try to decode, if it fails do nothing until the end
<5> logger.debug("Base64 decode attempt")
<6> try:
<7> result = base64.b64decode(text)
<8> # yeet turning b strings into normal stringy bois
<9> result = result.decode("utf-8")
<10> except UnicodeDecodeError as e:
<11> None
<12> except binascii.Error as e:
<13> None
<14> except ValueError:
<15> None
<16>
<17> if self.lc.checkLanguage(result):
<18> logger.debug(f"Base64 successful, returning {result}")
<19> return self.goodRet(result, cipher="Base64")
<20>
<21> # Base32
<22> logger.debug("attempting base32")
<23> try:
<24> result = base64.b32decode(text)
<25> # yeet turning b strings into normal stringy bois
<26> result = result.decode("utf-8")
<27> except UnicodeDecodeError as e:
<28> None
<29> except binascii.Error as e:
<30> None
<31> except ValueError:
<32> None
<33>
<34> if self.lc.checkLanguage(result):
<35> logger.debug(f"base32 successful, {result}")
<36> return self.goodRet(result, cipher="Base32")
<37>
<38> # Base16
<39> logger.debug("Attempting base16")
<40> try:
<41> result = base64.b16decode(text)
<42> # yeet turning b strings into normal stringy bois
<43> result = result.decode("utf-8")
<44> except UnicodeDecodeError as e:
<45> None
<46> except binascii.</s>
|
===========below chunk 0===========
# module: ciphey.Decryptor.Encoding.base64
class Base64:
def decrypt(self, text):
# offset: 1
None
except ValueError:
None
if self.lc.checkLanguage(result):
logger.debug(f"Base16 successful, {result}")
return self.goodRet(result, cipher="Base16")
# Base85
logger.debug("Attempting base85")
try:
result = base64.b85decode(text)
# yeet turning b strings into normal stringy bois
result = result.decode("utf-8")
except UnicodeDecodeError as e:
None
except binascii.Error as e:
None
except ValueError:
None
if self.lc.checkLanguage(result):
logger.debug(f"Base85 successful, {result}")
return self.goodRet(result, cipher="Base85")
# if nothing works, it has failed.
return self.badRet()
===========unchanged ref 0===========
at: base64
b64decode(s: _decodable, altchars: Optional[bytes]=..., validate: bool=...) -> bytes
b32decode(s: _decodable, casefold: bool=..., map01: Optional[bytes]=...) -> bytes
b16decode(s: _decodable, casefold: bool=...) -> bytes
b85decode(b: _decodable) -> bytes
at: binascii
Error(*args: object)
at: ciphey.Decryptor.Encoding.base64.Base64
goodRet(result, cipher)
badRet()
at: ciphey.Decryptor.Encoding.base64.Base64.__init__
self.lc = lc
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
|
ciphey.languageCheckerMod.chisquared/chiSquared.__init__
|
Modified
|
Ciphey~Ciphey
|
000ac7508167684dcfb20cd855ed02f6e56e8ebf
|
Merge branch 'master' of github.com:Ciphey/Ciphey
|
<0>:<del> self.languages = {
<1>:<del> "English":
<2>:<del> # [0.0855, 0.0160, 0.0316, 0.0387, 0.1210,0.0218, 0.0209, 0.0496, 0.0733, 0.0022,0.0081, 0.0421, 0.0253, 0.0717, 0.0747,0.0207, 0.0010, 0.0633, 0.0673, 0.0894,0.0268, 0.0106, 0.0183, 0.0019, 0.0172,0.0011]
<3>:<del> # {'A': 8.12, 'B': 1.49, 'C': 2.71, 'D': 4.32, 'E': 12.02, 'F': 2.3, 'G': 2.03, 'H': 5.92, 'I': 7.31, 'J': 0.1, 'K': 0.69, 'L': 3.98, 'M': 2.61, 'N': 6.95, 'O': 7.68, 'P': 1.82, 'Q': 0.11, 'R': 6.02, 'S': 6.28, 'T': 9.1, 'U': 2.88, 'V': 1.11, 'W': 2.09, 'X': 0.17, 'Y': 2.11, 'Z': 0.07}
<4>:<del> [
<5>:<del> 0.0812,
<6>:<del> 0.0271,
<7>:<del> 0.0149,
<8>:<del> 0.1202,
<9>:<del> 0.0432,
<10>:<del> 0.0203,
<11>:<del> 0.023,
<12>:<del> 0.0731,
<13>:<del> 0.0592,
<14>:<del> 0.0069,
<15>:<del> 0.001,
<16>:<del> 0.026099999999999998,
<17>:<del> 0.0398,
<18>:<del> 0.0768,
|
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def __init__(self):
<0> self.languages = {
<1> "English":
<2> # [0.0855, 0.0160, 0.0316, 0.0387, 0.1210,0.0218, 0.0209, 0.0496, 0.0733, 0.0022,0.0081, 0.0421, 0.0253, 0.0717, 0.0747,0.0207, 0.0010, 0.0633, 0.0673, 0.0894,0.0268, 0.0106, 0.0183, 0.0019, 0.0172,0.0011]
<3> # {'A': 8.12, 'B': 1.49, 'C': 2.71, 'D': 4.32, 'E': 12.02, 'F': 2.3, 'G': 2.03, 'H': 5.92, 'I': 7.31, 'J': 0.1, 'K': 0.69, 'L': 3.98, 'M': 2.61, 'N': 6.95, 'O': 7.68, 'P': 1.82, 'Q': 0.11, 'R': 6.02, 'S': 6.28, 'T': 9.1, 'U': 2.88, 'V': 1.11, 'W': 2.09, 'X': 0.17, 'Y': 2.11, 'Z': 0.07}
<4> [
<5> 0.0812,
<6> 0.0271,
<7> 0.0149,
<8> 0.1202,
<9> 0.0432,
<10> 0.0203,
<11> 0.023,
<12> 0.0731,
<13> 0.0592,
<14> 0.0069,
<15> 0.001,
<16> 0.026099999999999998,
<17> 0.0398,
<18> 0.0768,</s>
|
===========below chunk 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def __init__(self):
# offset: 1
0.0695,
0.0011,
0.0182,
0.06280000000000001,
0.0602,
0.0288,
0.091,
0.0209,
0.0111,
0.021099999999999997,
0.0017000000000000001,
0.0007000000000000001,
]
}
self.average = 0.0
self.totalDone = 0.0
self.oldAverage = 0.0
self.mh = mh.mathsHelper()
self.highestLanguage = ""
self.totalChi = 0.0
self.totalEqual = False
self.chisAsaList = []
# these are settings that may impact how the program works overall
self.chiSquaredSignificaneThreshold = 1 # how many stds you want to go below it
self.totalDoneThreshold = 10
self.standarddeviation = 0.00 # the standard deviation I use
self.oldstandarddeviation = 0.00
===========unchanged ref 0===========
at: ciphey.mathsHelper
mathsHelper()
|
ciphey.languageCheckerMod.chisquared/chiSquared.checkChi
|
Modified
|
Ciphey~Ciphey
|
000ac7508167684dcfb20cd855ed02f6e56e8ebf
|
Merge branch 'master' of github.com:Ciphey/Ciphey
|
<0>:<add> if text is None:
<del> if text == None:
<2>:<add> if type(text) is bytes:
<add> try: text = text.decode()
<add> except: return None
<16>:<add> analysis = cipheycore.analyse_string(text)
<del> self.chiSquared(text)
<20>:<del> stdSignif = float(
<21>:<del> self.average
<22>:<del> - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
<23>:<del> )
<24>:<del> tempy = abs(
<25>:<del> self.average
<26>:<del> - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
<27>:<del> )
<28>:<del> if (
<29>:<del> self.chisAsaList[-1] <= abs(stdSignif)
<30>:<del> or self.totalDone < self.totalDoneThreshold
<31>:<del> or self.totalEqual
<32>:<del> # or float(self.chisAsaList[-1]) < stdSignif + 0.1
<33>:<del> # or float(self.chisAsaList[-1]) > stdSignif - 0.1
<34>:<del> ):
<35>:<del> logger.debug(f"Chi squared returns true for {text}")
|
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
<0> if text == None:
<1> return False
<2> """Checks to see if the Chi score is good
<3> if it is, it returns True
<4> Call this when you want to determine whether something is likely to be Chi or not
<5>
<6> Arguments:
<7> * text - the text you want to run a Chi Squared score on
<8>
<9> Outputs:
<10> * True - if it has a significantly lower chi squared score
<11> * False - if it doesn't have a significantly lower chi squared score
<12> """
<13> # runs after every chi squared to see if it's 1 significantly lower than averae
<14> # the or statement is bc if the program has just started I don't want it to ignore the
<15> # ones at the start
<16> self.chiSquared(text)
<17> # If the latest chi squared is less than the standard deviation
<18> # or if not many chi squares have been calculated
<19> # or if every single letter in a text appears exactly once (pangram)
<20> stdSignif = float(
<21> self.average
<22> - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
<23> )
<24> tempy = abs(
<25> self.average
<26> - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
<27> )
<28> if (
<29> self.chisAsaList[-1] <= abs(stdSignif)
<30> or self.totalDone < self.totalDoneThreshold
<31> or self.totalEqual
<32> # or float(self.chisAsaList[-1]) < stdSignif + 0.1
<33> # or float(self.chisAsaList[-1]) > stdSignif - 0.1
<34> ):
<35> logger.debug(f"Chi squared returns true for {text}")</s>
|
===========below chunk 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
# offset: 1
return True
else:
return False
===========changed ref 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def __add__(self, otherChiSquared):
- """
- each language checker has its own intance of chi squared
- so to add 2 languae checkers together we add their chi squared together
- """
- addedObject = chiSquared()
- addedObject.average = self.average + otherChiSquared.average
- addedObject.totalDone = self.totalDone + otherChiSquared.totalDone
- addedObject.totalChi = self.totalChi + otherChiSquared.totalChi
- addedObject.chisAsaList = self.chisAsaList + otherChiSquared.chisAsaList
- return addedObject
-
===========changed ref 1===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def __init__(self):
- self.languages = {
- "English":
- # [0.0855, 0.0160, 0.0316, 0.0387, 0.1210,0.0218, 0.0209, 0.0496, 0.0733, 0.0022,0.0081, 0.0421, 0.0253, 0.0717, 0.0747,0.0207, 0.0010, 0.0633, 0.0673, 0.0894,0.0268, 0.0106, 0.0183, 0.0019, 0.0172,0.0011]
- # {'A': 8.12, 'B': 1.49, 'C': 2.71, 'D': 4.32, 'E': 12.02, 'F': 2.3, 'G': 2.03, 'H': 5.92, 'I': 7.31, 'J': 0.1, 'K': 0.69, 'L': 3.98, 'M': 2.61, 'N': 6.95, 'O': 7.68, 'P': 1.82, 'Q': 0.11, 'R': 6.02, 'S': 6.28, 'T': 9.1, 'U': 2.88, 'V': 1.11, 'W': 2.09, 'X': 0.17, 'Y': 2.11, 'Z': 0.07}
- [
- 0.0812,
- 0.0271,
- 0.0149,
- 0.1202,
- 0.0432,
- 0.0203,
- 0.023,
- 0.0731,
- 0.0592,
- 0.0069,
- 0.001,
- 0.026099999999999998,
- 0.0398,
- 0.0768,</s>
===========changed ref 2===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def __init__(self):
# offset: 1
<s> <del> 0.026099999999999998,
- 0.0398,
- 0.0768,
- 0.0695,
- 0.0011,
- 0.0182,
- 0.06280000000000001,
- 0.0602,
- 0.0288,
- 0.091,
- 0.0209,
- 0.0111,
- 0.021099999999999997,
- 0.0017000000000000001,
- 0.0007000000000000001,
- ]
- }
+ self.language = cipheydists.get_dist("twist")
self.average = 0.0
self.totalDone = 0.0
self.oldAverage = 0.0
self.mh = mh.mathsHelper()
self.highestLanguage = ""
self.totalChi = 0.0
self.totalEqual = False
self.chisAsaList = []
# these are settings that may impact how the program works overall
- self.chiSquaredSignificaneThreshold = 1 # how many stds you want to go below it
- self.totalDoneThreshold = 10
-
- self.standarddeviation = 0.00 # the standard deviation I use
- self.oldstandarddeviation = 0.00
+ self.chiSquaredSignificanceThreshold = 0.001 # The p value that we reject below
|
ciphey.Decryptor.basicEncryption.basic_parent/BasicParent.decrypt
|
Modified
|
Ciphey~Ciphey
|
000ac7508167684dcfb20cd855ed02f6e56e8ebf
|
Merge branch 'master' of github.com:Ciphey/Ciphey
|
<3>:<add> pool = ThreadPool(16)
<del> pool = ThreadPool(4)
<11>:<add> # self.lc = self.lc + answer["lc"]
<del> self.lc = self.lc + answer["lc"]
|
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
<0> self.text = text
<1> from multiprocessing.dummy import Pool as ThreadPool
<2>
<3> pool = ThreadPool(4)
<4> answers = pool.map(self.callDecrypt, self.list_of_objects)
<5>
<6> """for item in self.list_of_objects:
<7> result = item.decrypt(text)
<8> answers.append(result)"""
<9> for answer in answers:
<10> # adds the LC objects together
<11> self.lc = self.lc + answer["lc"]
<12> if answer["IsPlaintext?"]:
<13> return answer
<14>
<15> # so vigenere runs ages
<16> # and you cant kill threads in a pool
<17> # so i just run it last lol]
<18> #
<19> # Not anymore! #basedcore
<20>
<21> result = self.callDecrypt(self.vigenere)
<22> if result["IsPlaintext?"]:
<23> return result
<24>
<25> return {
<26> "lc": self.lc,
<27> "IsPlaintext?": False,
<28> "Plaintext": None,
<29> "Cipher": None,
<30> "Extra Information": None,
<31> }
<32>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent
callDecrypt(obj)
at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent.__init__
self.lc = lc
self.vigenere = vi.Vigenere(self.lc)
self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans]
at: multiprocessing.dummy
Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any
===========changed ref 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def __add__(self, otherChiSquared):
- """
- each language checker has its own intance of chi squared
- so to add 2 languae checkers together we add their chi squared together
- """
- addedObject = chiSquared()
- addedObject.average = self.average + otherChiSquared.average
- addedObject.totalDone = self.totalDone + otherChiSquared.totalDone
- addedObject.totalChi = self.totalChi + otherChiSquared.totalChi
- addedObject.chisAsaList = self.chisAsaList + otherChiSquared.chisAsaList
- return addedObject
-
===========changed ref 1===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def myChi(self, text, distribution):
- """My own implementation of Chi squared using the two resources mention in the comments on this definition as guidance"""
- # https://cgi.csc.liv.ac.uk/~john/comp105resources/lecture10.pdf
- # http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared-statistic/
- # given a text frequency and a distribution, calculate it's Chi score
- chiScore = 0.0
- for counter, letter in enumerate(text.values()):
- try:
- chiScore = (
- chiScore
- + ((letter - distribution[counter]) ** 2) / distribution[counter]
- )
- except IndexError as e:
- return True
- return chiScore
-
===========changed ref 2===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def getLetterFreq(self, text):
- # This part creates a letter frequency of the text
- letterFreq = {
- "a": 0,
- "b": 0,
- "c": 0,
- "d": 0,
- "e": 0,
- "f": 0,
- "g": 0,
- "h": 0,
- "i": 0,
- "j": 0,
- "k": 0,
- "l": 0,
- "m": 0,
- "n": 0,
- "o": 0,
- "p": 0,
- "q": 0,
- "r": 0,
- "s": 0,
- "t": 0,
- "u": 0,
- "v": 0,
- "w": 0,
- "x": 0,
- "y": 0,
- "z": 0,
- }
-
- for letter in text.lower():
- if letter in letterFreq:
- letterFreq[letter] += 1
- else:
- # if letter is not puncuation, but it is still ascii
- # it's probably a different language so add it to the dict
- if (
- str(letter) not in punctuation
- and self.mh.isAscii(letter)
- and str(letter) not in NUMBERS
- ):
- letterFreq[letter] = 1
- return letterFreq
-
===========changed ref 3===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
+ if text is None:
- if text == None:
return False
+ if type(text) is bytes:
+ try: text = text.decode()
+ except: return None
"""Checks to see if the Chi score is good
if it is, it returns True
Call this when you want to determine whether something is likely to be Chi or not
Arguments:
* text - the text you want to run a Chi Squared score on
Outputs:
* True - if it has a significantly lower chi squared score
* False - if it doesn't have a significantly lower chi squared score
"""
# runs after every chi squared to see if it's 1 significantly lower than averae
# the or statement is bc if the program has just started I don't want it to ignore the
# ones at the start
+ analysis = cipheycore.analyse_string(text)
- self.chiSquared(text)
# If the latest chi squared is less than the standard deviation
# or if not many chi squares have been calculated
# or if every single letter in a text appears exactly once (pangram)
- stdSignif = float(
- self.average
- - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
- )
- tempy = abs(
- self.average
- - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
- )
- if (
- self.chisAsaList[-1] <= abs(stdSignif)
- or self.totalDone < self.totalDoneThreshold
- or self.totalEqual
- # or float(self.chisAsaList[-1]) < stdSignif + 0.1
- # or float(self.</s>
===========changed ref 4===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
# offset: 1
<s> float(self.chisAsaList[-1]) < stdSignif + 0.1
- # or float(self.chisAsaList[-1]) > stdSignif - 0.1
- ):
- logger.debug(f"Chi squared returns true for {text}")
- return True
- else:
- return False
+ return cipheycore.chisq_test(analysis, self.language) > 0.001
|
ciphey.Decryptor.Encoding.encodingParent/EncodingParent.decrypt
|
Modified
|
Ciphey~Ciphey
|
000ac7508167684dcfb20cd855ed02f6e56e8ebf
|
Merge branch 'master' of github.com:Ciphey/Ciphey
|
<18>:<add> # self.lc = self.lc + answer["lc"]
<del> self.lc = self.lc + answer["lc"]
|
# module: ciphey.Decryptor.Encoding.encodingParent
class EncodingParent:
def decrypt(self, text):
<0> self.text = text
<1> torun = [self.base64, self.binary, self.hex, self.ascii, self.morse]
<2> logger.debug(f"Encoding parent is running {torun}")
<3> """
<4> ok so I have an array of functions
<5> and I want to apply each function to some text
<6> (text, function)
<7> but the way it works is you apply text to every item in the array (function)
<8>
<9> """
<10> from multiprocessing.dummy import Pool as ThreadPool
<11>
<12> pool = ThreadPool(4)
<13> answers = pool.map(self.callDecrypt, torun)
<14>
<15> for answer in answers:
<16> logger.debug(f"All answers are {answers}")
<17> # adds the LC objects together
<18> self.lc = self.lc + answer["lc"]
<19> if answer["IsPlaintext?"]:
<20> logger.debug(f"Plaintext found {answer}")
<21> return answer
<22> return {
<23> "lc": self.lc,
<24> "IsPlaintext?": False,
<25> "Plaintext": None,
<26> "Cipher": None,
<27> "Extra Information": None,
<28> }
<29>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent
callDecrypt(obj)
at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent.__init__
self.lc = lc
self.base64 = Base64(self.lc)
self.binary = Binary(self.lc)
self.hex = Hexadecimal(self.lc)
self.ascii = Ascii(self.lc)
self.morse = MorseCode(self.lc)
at: multiprocessing.dummy
Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any
===========changed ref 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def __add__(self, otherChiSquared):
- """
- each language checker has its own intance of chi squared
- so to add 2 languae checkers together we add their chi squared together
- """
- addedObject = chiSquared()
- addedObject.average = self.average + otherChiSquared.average
- addedObject.totalDone = self.totalDone + otherChiSquared.totalDone
- addedObject.totalChi = self.totalChi + otherChiSquared.totalChi
- addedObject.chisAsaList = self.chisAsaList + otherChiSquared.chisAsaList
- return addedObject
-
===========changed ref 1===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def myChi(self, text, distribution):
- """My own implementation of Chi squared using the two resources mention in the comments on this definition as guidance"""
- # https://cgi.csc.liv.ac.uk/~john/comp105resources/lecture10.pdf
- # http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared-statistic/
- # given a text frequency and a distribution, calculate it's Chi score
- chiScore = 0.0
- for counter, letter in enumerate(text.values()):
- try:
- chiScore = (
- chiScore
- + ((letter - distribution[counter]) ** 2) / distribution[counter]
- )
- except IndexError as e:
- return True
- return chiScore
-
===========changed ref 2===========
# module: ciphey.Decryptor.basicEncryption.basic_parent
class BasicParent:
def decrypt(self, text):
self.text = text
from multiprocessing.dummy import Pool as ThreadPool
+ pool = ThreadPool(16)
- pool = ThreadPool(4)
answers = pool.map(self.callDecrypt, self.list_of_objects)
"""for item in self.list_of_objects:
result = item.decrypt(text)
answers.append(result)"""
for answer in answers:
# adds the LC objects together
+ # self.lc = self.lc + answer["lc"]
- self.lc = self.lc + answer["lc"]
if answer["IsPlaintext?"]:
return answer
# so vigenere runs ages
# and you cant kill threads in a pool
# so i just run it last lol]
#
# Not anymore! #basedcore
result = self.callDecrypt(self.vigenere)
if result["IsPlaintext?"]:
return result
return {
"lc": self.lc,
"IsPlaintext?": False,
"Plaintext": None,
"Cipher": None,
"Extra Information": None,
}
===========changed ref 3===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
-
- def getLetterFreq(self, text):
- # This part creates a letter frequency of the text
- letterFreq = {
- "a": 0,
- "b": 0,
- "c": 0,
- "d": 0,
- "e": 0,
- "f": 0,
- "g": 0,
- "h": 0,
- "i": 0,
- "j": 0,
- "k": 0,
- "l": 0,
- "m": 0,
- "n": 0,
- "o": 0,
- "p": 0,
- "q": 0,
- "r": 0,
- "s": 0,
- "t": 0,
- "u": 0,
- "v": 0,
- "w": 0,
- "x": 0,
- "y": 0,
- "z": 0,
- }
-
- for letter in text.lower():
- if letter in letterFreq:
- letterFreq[letter] += 1
- else:
- # if letter is not puncuation, but it is still ascii
- # it's probably a different language so add it to the dict
- if (
- str(letter) not in punctuation
- and self.mh.isAscii(letter)
- and str(letter) not in NUMBERS
- ):
- letterFreq[letter] = 1
- return letterFreq
-
===========changed ref 4===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
+ if text is None:
- if text == None:
return False
+ if type(text) is bytes:
+ try: text = text.decode()
+ except: return None
"""Checks to see if the Chi score is good
if it is, it returns True
Call this when you want to determine whether something is likely to be Chi or not
Arguments:
* text - the text you want to run a Chi Squared score on
Outputs:
* True - if it has a significantly lower chi squared score
* False - if it doesn't have a significantly lower chi squared score
"""
# runs after every chi squared to see if it's 1 significantly lower than averae
# the or statement is bc if the program has just started I don't want it to ignore the
# ones at the start
+ analysis = cipheycore.analyse_string(text)
- self.chiSquared(text)
# If the latest chi squared is less than the standard deviation
# or if not many chi squares have been calculated
# or if every single letter in a text appears exactly once (pangram)
- stdSignif = float(
- self.average
- - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
- )
- tempy = abs(
- self.average
- - (self.oldstandarddeviation * self.chiSquaredSignificaneThreshold)
- )
- if (
- self.chisAsaList[-1] <= abs(stdSignif)
- or self.totalDone < self.totalDoneThreshold
- or self.totalEqual
- # or float(self.chisAsaList[-1]) < stdSignif + 0.1
- # or float(self.</s>
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.checkDictionary
|
Modified
|
Ciphey~Ciphey
|
28bd9ad10e04c64d258df186dc5d27837f303cc7
|
Move more to cipheydists
|
<6>:<del> # can dynamically use languages then
<7>:<del> language = str(language) + ".txt"
<9>:<del> # https://stackoverflow.com/questions/7165749/open-file-in-a-relative-location-in-python
<10>:<del> script_dir = os.path.dirname(__file__)
<11>:<del> file_path = os.path.join(script_dir, "English.txt")
<12>:<del> file = open(file_path, "r")
<13>:<del> f = file.readlines()
<14>:<del> file.close()
<15>:<del> f = [x.strip().lower() for x in f]
<16>:<del> # dictionary is "word\n" so I remove the "\n"
<17>:<add> f = cipheydists.get_list(language)
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def checkDictionary(self, text, language):
<0> """Compares a word with
<1> The dictionary is sorted and the text is sorted"""
<2> # reads through most common words / passwords
<3> # and calculates how much of that is in language
<4> text = self.cleanText(text)
<5> text.sort()
<6> # can dynamically use languages then
<7> language = str(language) + ".txt"
<8>
<9> # https://stackoverflow.com/questions/7165749/open-file-in-a-relative-location-in-python
<10> script_dir = os.path.dirname(__file__)
<11> file_path = os.path.join(script_dir, "English.txt")
<12> file = open(file_path, "r")
<13> f = file.readlines()
<14> file.close()
<15> f = [x.strip().lower() for x in f]
<16> # dictionary is "word\n" so I remove the "\n"
<17>
<18> # so this should loop until it gets to the point in the @staticmethod
<19> # that equals the word :)
<20>
<21> """
<22> for every single word in main dictionary
<23> if that word == text[0] then +1 to counter
<24> then +1 to text[0 + i]
<25> so say the dict is ordered
<26> we just loop through dict
<27> and eventually we'll reach a point where word in dict = word in text
<28> at that point, we move to the next text point
<29> both text and dict are sorted
<30> so we only loop once, we can do this in O(n log n) time
<31> """
<32> counter = 0
<33> counter_percent = 0
<34>
<35> for dictLengthCounter, word in enumerate(f):
<36> # if there is more words counted than there is text
<37> # it is 100%,</s>
|
===========below chunk 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def checkDictionary(self, text, language):
# offset: 1
# so this stops that
if counter >= len(text):
break
# if the dictionary word is contained in the text somewhere
# counter + 1
if word in text:
counter = counter + 1
counter_percent = counter_percent + 1
self.languageWordsCounter = counter
self.languagePercentage = self.mh.percentage(
float(self.languageWordsCounter), float(len(text))
)
return counter
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
self.mh = mh.mathsHelper()
self.languagePercentage = 0.0
self.languageWordsCounter = 0.0
self.languageThreshold = 55
# this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
# dictionary because lookup is O(1)
- self.top1000Words = {
- "able": None,
- "about": None,
- "above": None,
- "act": None,
- "add": None,
- "afraid": None,
- "after": None,
- "again": None,
- "against": None,
- "age": None,
- "ago": None,
- "agree": None,
- "air": None,
- "all": None,
- "allow": None,
- "also": None,
- "always": None,
- "am": None,
- "among": None,
- "an": None,
- "and": None,
- "anger": None,
- "animal": None,
- "answer": None,
- "any": None,
- "appear": None,
- "apple": None,
- "are": None,
- "area": None,
- "arm": None,
- "arrange": None,
- "arrive": None,
- "art": None,
- "as": None,
- "ask": None,
- "at": None,
- "atom": None,
- "baby": None,
- "back": None,
- "bad": None,
- "ball": None,
</s>
===========changed ref 1===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
# offset: 1
<s>,
- "back": None,
- "bad": None,
- "ball": None,
- "band": None,
- "bank": None,
- "bar": None,
- "base": None,
- "basic": None,
- "bat": None,
- "be": None,
- "bear": None,
- "beat": None,
- "beauty": None,
- "bed": None,
- "been": None,
- "before": None,
- "began": None,
- "begin": None,
- "behind": None,
- "believe": None,
- "bell": None,
- "best": None,
- "better": None,
- "between": None,
- "big": None,
- "bird": None,
- "bit": None,
- "black": None,
- "block": None,
- "blood": None,
- "blow": None,
- "blue": None,
- "board": None,
- "boat": None,
- "body": None,
- "bone": None,
- "book": None,
- "born": None,
- "both": None,
- "bottom": None,
- "bought": None,
- "box": None,
- "boy": None,
- "branch": None,
- "bread": None,
- "break": None,
- "bright</s>
===========changed ref 2===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
# offset: 2
<s>,
- "bring": None,
- "broad": None,
- "broke": None,
- "brother": None,
- "brought": None,
- "brown": None,
- "build": None,
- "burn": None,
- "busy": None,
- "but": None,
- "buy": None,
- "by": None,
- "call": None,
- "came": None,
- "camp": None,
- "can": None,
- "capital": None,
- "captain": None,
- "car": None,
- "card": None,
- "care": None,
- "carry": None,
- "case": None,
- "cat": None,
- "catch": None,
- "caught": None,
- "cause": None,
- "cell": None,
- "cent": None,
- "center": None,
- "century": None,
- "certain": None,
- "chair": None,
- "chance": None,
- "change": None,
- "character": None,
- "charge": None,
- "chart": None,
- "check": None,
- "chick": None,
- "chief": None,
- "child": None,
- "children": None,
- "choose": None,
- "chord": None,
- "circle": None,
</s>
|
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.checkLanguage
|
Modified
|
Ciphey~Ciphey
|
28bd9ad10e04c64d258df186dc5d27837f303cc7
|
Move more to cipheydists
|
<9>:<add> result2 = self.dictionary.confirmlanguage(text, "english")
<del> result2 = self.dictionary.confirmlanguage(text, "English")
|
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
def checkLanguage(self, text):
<0> logger.debug(f"In Language Checker with {text}")
<1> if text == "":
<2> return False
<3> result = self.chi.checkChi(text)
<4> wordsCheck = self.dictionary.check1000Words(text)
<5> if result or wordsCheck:
<6> logger.debug(
<7> f"Phase 1 complete. Result is {result} and 1000 words is {wordsCheck}"
<8> )
<9> result2 = self.dictionary.confirmlanguage(text, "English")
<10> logger.debug(f"Result is, dictionary checker, is {result2}")
<11> if result2:
<12> return True
<13> else:
<14> logger.debug(f"Phase 2 returns false")
<15> return False
<16> else:
<17> logger.debug(f"phase 1 returns false")
<18> return False
<19>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__add__
self.chi = new
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__init__
self.dictionary = dc.dictionaryChecker()
self.chi = cs.chiSquared()
at: ciphey.languageCheckerMod.chisquared.chiSquared
checkChi(text)
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
check1000Words(text)
at: languageCheckerMod.dictionaryChecker.dictionaryChecker
confirmlanguage(text, language)
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def checkDictionary(self, text, language):
"""Compares a word with
The dictionary is sorted and the text is sorted"""
# reads through most common words / passwords
# and calculates how much of that is in language
text = self.cleanText(text)
text.sort()
- # can dynamically use languages then
- language = str(language) + ".txt"
- # https://stackoverflow.com/questions/7165749/open-file-in-a-relative-location-in-python
- script_dir = os.path.dirname(__file__)
- file_path = os.path.join(script_dir, "English.txt")
- file = open(file_path, "r")
- f = file.readlines()
- file.close()
- f = [x.strip().lower() for x in f]
- # dictionary is "word\n" so I remove the "\n"
+ f = cipheydists.get_list(language)
# so this should loop until it gets to the point in the @staticmethod
# that equals the word :)
"""
for every single word in main dictionary
if that word == text[0] then +1 to counter
then +1 to text[0 + i]
so say the dict is ordered
we just loop through dict
and eventually we'll reach a point where word in dict = word in text
at that point, we move to the next text point
both text and dict are sorted
so we only loop once, we can do this in O(n log n) time
"""
counter = 0
counter_percent = 0
for dictLengthCounter, word in enumerate(f):
# if there is more words counted than there is text
# it is 100%, sometimes it goes over
# so this stops</s>
===========changed ref 1===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def checkDictionary(self, text, language):
# offset: 1
<s> if there is more words counted than there is text
# it is 100%, sometimes it goes over
# so this stops that
if counter >= len(text):
break
# if the dictionary word is contained in the text somewhere
# counter + 1
if word in text:
counter = counter + 1
counter_percent = counter_percent + 1
self.languageWordsCounter = counter
self.languagePercentage = self.mh.percentage(
float(self.languageWordsCounter), float(len(text))
)
return counter
===========changed ref 2===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
self.mh = mh.mathsHelper()
self.languagePercentage = 0.0
self.languageWordsCounter = 0.0
self.languageThreshold = 55
# this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
# dictionary because lookup is O(1)
- self.top1000Words = {
- "able": None,
- "about": None,
- "above": None,
- "act": None,
- "add": None,
- "afraid": None,
- "after": None,
- "again": None,
- "against": None,
- "age": None,
- "ago": None,
- "agree": None,
- "air": None,
- "all": None,
- "allow": None,
- "also": None,
- "always": None,
- "am": None,
- "among": None,
- "an": None,
- "and": None,
- "anger": None,
- "animal": None,
- "answer": None,
- "any": None,
- "appear": None,
- "apple": None,
- "are": None,
- "area": None,
- "arm": None,
- "arrange": None,
- "arrive": None,
- "art": None,
- "as": None,
- "ask": None,
- "at": None,
- "atom": None,
- "baby": None,
- "back": None,
- "bad": None,
- "ball": None,
</s>
===========changed ref 3===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
# offset: 1
<s>,
- "back": None,
- "bad": None,
- "ball": None,
- "band": None,
- "bank": None,
- "bar": None,
- "base": None,
- "basic": None,
- "bat": None,
- "be": None,
- "bear": None,
- "beat": None,
- "beauty": None,
- "bed": None,
- "been": None,
- "before": None,
- "began": None,
- "begin": None,
- "behind": None,
- "believe": None,
- "bell": None,
- "best": None,
- "better": None,
- "between": None,
- "big": None,
- "bird": None,
- "bit": None,
- "black": None,
- "block": None,
- "blood": None,
- "blow": None,
- "blue": None,
- "board": None,
- "boat": None,
- "body": None,
- "bone": None,
- "book": None,
- "born": None,
- "both": None,
- "bottom": None,
- "bought": None,
- "box": None,
- "boy": None,
- "branch": None,
- "bread": None,
- "break": None,
- "bright</s>
|
ciphey.languageCheckerMod.chisquared/chiSquared.checkChi
|
Modified
|
Ciphey~Ciphey
|
93e5552819f589f35f96515f87d7d138f73b0b2d
|
Fixed non-determinism for real defo sure this time absolutely!
|
<20>:<del> # If the latest chi squared is less than the standard deviation
<21>:<del> # or if not many chi squares have been calculated
<22>:<del> # or if every single letter in a text appears exactly once (pangram)
<23>:<add> chisq = cipheycore.chisq_test(analysis, self.language)
<del> return cipheycore.chisq_test(analysis, self.language) > 0.001
<24>:<add> logger.debug(
<add> f"Chi-squared p-value is {chisq}"
<add> )
<add> return chisq > self.chiSquaredSignificanceThreshold
|
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
<0> if text is None:
<1> return False
<2> if type(text) is bytes:
<3> try: text = text.decode()
<4> except: return None
<5> """Checks to see if the Chi score is good
<6> if it is, it returns True
<7> Call this when you want to determine whether something is likely to be Chi or not
<8>
<9> Arguments:
<10> * text - the text you want to run a Chi Squared score on
<11>
<12> Outputs:
<13> * True - if it has a significantly lower chi squared score
<14> * False - if it doesn't have a significantly lower chi squared score
<15> """
<16> # runs after every chi squared to see if it's 1 significantly lower than averae
<17> # the or statement is bc if the program has just started I don't want it to ignore the
<18> # ones at the start
<19> analysis = cipheycore.analyse_string(text)
<20> # If the latest chi squared is less than the standard deviation
<21> # or if not many chi squares have been calculated
<22> # or if every single letter in a text appears exactly once (pangram)
<23> return cipheycore.chisq_test(analysis, self.language) > 0.001
<24>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.chisquared.chiSquared.__init__
self.language = cipheydists.get_dist("twist")
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.check1000Words
|
Modified
|
Ciphey~Ciphey
|
93e5552819f589f35f96515f87d7d138f73b0b2d
|
Fixed non-determinism for real defo sure this time absolutely!
|
<0>:<add> if text is None:
<del> if text == None:
<15>:<del> else:
<16>:<add> return False
<del> return False
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def check1000Words(self, text):
<0> if text == None:
<1> return False
<2> check = dict.fromkeys(self.top1000Words)
<3> logger.debug(f"text before cleaning is {text}")
<4> text = self.cleanText(text)
<5> logger.debug(f"Check 1000 words text is {text}")
<6> # If any of the top 1000 words in the text appear
<7> # return true
<8> for word in text:
<9> logger.debug(f"Word in check1000 is {word}")
<10> # I was debating using any() here, but I think they're the
<11> # same speed so it doesn't really matter too much
<12> if word in check:
<13> logger.debug(f"Check 1000 words returns True for word {word}")
<14> return True
<15> else:
<16> return False
<17>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
cleanText(text)
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.__init__
self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
===========changed ref 0===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
if text is None:
return False
if type(text) is bytes:
try: text = text.decode()
except: return None
"""Checks to see if the Chi score is good
if it is, it returns True
Call this when you want to determine whether something is likely to be Chi or not
Arguments:
* text - the text you want to run a Chi Squared score on
Outputs:
* True - if it has a significantly lower chi squared score
* False - if it doesn't have a significantly lower chi squared score
"""
# runs after every chi squared to see if it's 1 significantly lower than averae
# the or statement is bc if the program has just started I don't want it to ignore the
# ones at the start
analysis = cipheycore.analyse_string(text)
- # If the latest chi squared is less than the standard deviation
- # or if not many chi squares have been calculated
- # or if every single letter in a text appears exactly once (pangram)
+ chisq = cipheycore.chisq_test(analysis, self.language)
- return cipheycore.chisq_test(analysis, self.language) > 0.001
+ logger.debug(
+ f"Chi-squared p-value is {chisq}"
+ )
+ return chisq > self.chiSquaredSignificanceThreshold
|
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.checkLanguage
|
Modified
|
Ciphey~Ciphey
|
93e5552819f589f35f96515f87d7d138f73b0b2d
|
Fixed non-determinism for real defo sure this time absolutely!
|
<4>:<del> wordsCheck = self.dictionary.check1000Words(text)
<5>:<del> if result or wordsCheck:
<6>:<add> if not result:
<7>:<add> f"Chi squared failed. Attempting 1000 words"
<del> f"Phase 1 complete. Result is {result} and 1000 words is {wordsCheck}"
<9>:<del> result2 = self.dictionary.confirmlanguage(text, "english")
<10>:<del> logger.debug(f"Result is, dictionary checker, is {result2}")
<11>:<del> if result2:
<12>:<del> return True
<13>:<del> else:
<14>:<del> logger.debug(f"Phase 2 returns false")
<15>:<add> if not self.dictionary.check1000Words(text):
<add> logger.debug(
<add> f"1000 words failed. This is not plaintext"
<add> )
<16>:<add>
<add> logger.debug(
<add> f"Language check phase 1 complete"
<add> )
<del> else:
<17>:<add> result2 = self.dictionary.confirmlanguage(text, "english")
<add> logger.debug(f"Result is, dictionary checker, is {result2}")
<add> if not result2:
<add> logger.debug(f"Language check phase 2 returns false")
<del> logger.debug(f"phase 1 returns false")
<19>:<add> return True
|
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
def checkLanguage(self, text):
<0> logger.debug(f"In Language Checker with {text}")
<1> if text == "":
<2> return False
<3> result = self.chi.checkChi(text)
<4> wordsCheck = self.dictionary.check1000Words(text)
<5> if result or wordsCheck:
<6> logger.debug(
<7> f"Phase 1 complete. Result is {result} and 1000 words is {wordsCheck}"
<8> )
<9> result2 = self.dictionary.confirmlanguage(text, "english")
<10> logger.debug(f"Result is, dictionary checker, is {result2}")
<11> if result2:
<12> return True
<13> else:
<14> logger.debug(f"Phase 2 returns false")
<15> return False
<16> else:
<17> logger.debug(f"phase 1 returns false")
<18> return False
<19>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__add__
self.chi = new
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__init__
self.dictionary = dc.dictionaryChecker()
self.chi = cs.chiSquared()
at: ciphey.languageCheckerMod.chisquared.chiSquared
checkChi(text)
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
check1000Words(text)
confirmlanguage(text, language)
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def check1000Words(self, text):
+ if text is None:
- if text == None:
return False
check = dict.fromkeys(self.top1000Words)
logger.debug(f"text before cleaning is {text}")
text = self.cleanText(text)
logger.debug(f"Check 1000 words text is {text}")
# If any of the top 1000 words in the text appear
# return true
for word in text:
logger.debug(f"Word in check1000 is {word}")
# I was debating using any() here, but I think they're the
# same speed so it doesn't really matter too much
if word in check:
logger.debug(f"Check 1000 words returns True for word {word}")
return True
- else:
+ return False
- return False
===========changed ref 1===========
# module: ciphey.languageCheckerMod.chisquared
class chiSquared:
def checkChi(self, text):
if text is None:
return False
if type(text) is bytes:
try: text = text.decode()
except: return None
"""Checks to see if the Chi score is good
if it is, it returns True
Call this when you want to determine whether something is likely to be Chi or not
Arguments:
* text - the text you want to run a Chi Squared score on
Outputs:
* True - if it has a significantly lower chi squared score
* False - if it doesn't have a significantly lower chi squared score
"""
# runs after every chi squared to see if it's 1 significantly lower than averae
# the or statement is bc if the program has just started I don't want it to ignore the
# ones at the start
analysis = cipheycore.analyse_string(text)
- # If the latest chi squared is less than the standard deviation
- # or if not many chi squares have been calculated
- # or if every single letter in a text appears exactly once (pangram)
+ chisq = cipheycore.chisq_test(analysis, self.language)
- return cipheycore.chisq_test(analysis, self.language) > 0.001
+ logger.debug(
+ f"Chi-squared p-value is {chisq}"
+ )
+ return chisq > self.chiSquaredSignificanceThreshold
|
ciphey.mathsHelper/mathsHelper.gcd
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<0>:<add> """Greatest common divisor.
<add>
<add> The Greatest Common Divisor of a and b using Euclid's Algorithm.
<del> # Return the Greatest Common Divisor of a and b using Euclid's Algorithm
<1>:<add>
<add> Args:
<add> a -> num 1
<add> b -> num 2
<add>
<add> Returns:
<add> Returns GCD(a, b)
<add>
<add> """
<add> # Return
|
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def gcd(a, b) -> int:
- def gcd(self, a, b):
<0> # Return the Greatest Common Divisor of a and b using Euclid's Algorithm
<1> while a != 0:
<2> a, b = b % a, a
<3> return b
<4>
| |
ciphey.mathsHelper/mathsHelper.percentage
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<0>:<add> """Returns percentage.
<add>
<add> Just a normal algorithm to return the percent.
<add>
<add> Args:
<add> part -> part of the whole number
<add> whole -> the whole number
<add>
<add> Returns:
<add> Returns the percentage of part to whole.
<add>
<add> """
<del> """Works with percentages"""
<1>:<del> # yeah uhm sometimes I'm a dummy dum dum and I think dividing by 0 is a good idea
<2>:<del> # this if statememt is to stop my stupidity
|
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def percentage(part: float, whole: float) -> float:
- def percentage(self, part, whole):
<0> """Works with percentages"""
<1> # yeah uhm sometimes I'm a dummy dum dum and I think dividing by 0 is a good idea
<2> # this if statememt is to stop my stupidity
<3> if part <= 0 or whole <= 0:
<4> return 0
<5> # works with percentages
<6> return 100 * float(part) / float(whole)
<7>
|
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def gcd(a, b) -> int:
- def gcd(self, a, b):
+ """Greatest common divisor.
+
+ The Greatest Common Divisor of a and b using Euclid's Algorithm.
- # Return the Greatest Common Divisor of a and b using Euclid's Algorithm
+
+ Args:
+ a -> num 1
+ b -> num 2
+
+ Returns:
+ Returns GCD(a, b)
+
+ """
+ # Return
while a != 0:
a, b = b % a, a
return b
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def findModInverse(self, a, m):
- # Return the modular inverse of a % m, which is
- # the number x such that a*x % m = 1
-
- if gcd(a, m) != 1:
- return None # No mod inverse exists if a & m aren't relatively prime.
-
- # Calculate using the Extended Euclidean Algorithm:
- u1, u2, u3 = 1, 0, a
- v1, v2, v3 = 0, 1, m
- while v3 != 0:
- q = u3 // v3 # Note that // is the integer division operator
- v1, v2, v3, u1, u2, u3 = (
- (u1 - q * v1),
- (u2 - q * v2),
- (u3 - q * v3),
- v1,
- v2,
- v3,
- )
- return u1 % m
-
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def find_mod_inverse(a: int, m: int) -> int:
+ """Return the modular inverse of a % m.
+
+ Which is the number x such that a*x % m = 1. Calculated using the Extended Euclidean Algorithm.
+
+ Args:
+ a -> num 1
+ m -> num 2
+
+ Returns:
+ Returns modular inverse(u1, m)
+
+ """
+ # Return the modular inverse of a % m, which is
+ # the number x such that a*x % m = 1
+
+ if gcd(a, m) != 1:
+ return None # No mod inverse exists if a & m aren't relatively prime.
+
+ # Calculate using the Extended Euclidean Algorithm:
+ u1, u2, u3 = 1, 0, a
+ v1, v2, v3 = 0, 1, m
+ while v3 != 0:
+ q = u3 // v3 # Note that // is the integer division operator
+ v1, v2, v3, u1, u2, u3 = (
+ (u1 - q * v1),
+ (u2 - q * v2),
+ (u3 - q * v3),
+ v1,
+ v2,
+ v3,
+ )
+ return u1 % m
+
|
ciphey.Decryptor.basicEncryption.reverse/Reverse.decrypt
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<1>:<add> message = self.mh.strip_puncuation(message)
<del> message = self.mh.stripPuncuation(message)
|
# module: ciphey.Decryptor.basicEncryption.reverse
class Reverse:
def decrypt(self, message):
<0> logger.debug("In reverse")
<1> message = self.mh.stripPuncuation(message)
<2>
<3> message = message[::-1]
<4> result = self.lc.checkLanguage(message)
<5> if result:
<6> logger.debug("Reverse returns True")
<7> return {
<8> "lc": self.lc,
<9> "IsPlaintext?": True,
<10> "Plaintext": message,
<11> "Cipher": "Reverse",
<12> "Extra Information": None,
<13> }
<14> else:
<15> logger.debug(f"Reverse returns False")
<16> return {
<17> "lc": self.lc,
<18> "IsPlaintext?": False,
<19> "Plaintext": None,
<20> "Cipher": "Reverse",
<21> "Extra Information": None,
<22> }
<23>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.reverse.Reverse.__init__
self.lc = lc
self.mh = mh.mathsHelper()
at: ciphey.mathsHelper.mathsHelper
strip_puncuation(text: str) -> str
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def strip_puncuation(text: str) -> str:
+ """Strips punctuation from a given string.
+
+ Uses string.puncuation.
+
+ Args:
+ text -> the text to strip puncuation from.
+
+ Returns:
+ Returns string without puncuation.
+
+ """
+ text: str = str(text).translate(str.maketrans("", "", punctuation))
+ return text
+
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def getItemAtIndexZero(self, items):
- return items[0]
-
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def get_item_at_index_zero(items):
+ """Gets the item at index 0 from an iterable"""
+ return items[0]
+
===========changed ref 3===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def stripPuncuation(self, text):
- """Strips punctuation from a given string"""
- text = str(text).translate(str.maketrans("", "", punctuation))
- return text
-
===========changed ref 4===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def checkEqual(self, a):
- """checks if all items in an iterable are the same
- https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical"""
- return a.count(a[0]) == len(a)
-
===========changed ref 5===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def sortDictionary(self, dictionary):
- """Sorts a dictionary"""
- ret = dict(OrderedDict(sorted(dictionary.items())))
- logger.debug(
- f"The old dictionary was {dictionary} and I am sorting it to {ret}"
- )
- return ret
-
===========changed ref 6===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def isAscii(self, letter):
- """Determines whether a letter (or word) is ASCII"""
- # checks if a charecter is ascii
- # https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii
- return bool(lambda s: len(s) == len(s.encode()))
-
===========changed ref 7===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def check_equal(a) -> bool:
+ """checks if all items in an iterable are the same.
+
+ https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical
+
+ Args:
+ a -> an iterable
+
+ Returns:
+ Returns boolean.
+
+ """
+ return a.count(a[0]) == len(a)
+
===========changed ref 8===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def sort_dictionary(dictionary: dict) -> dict:
+ """Sorts a dictionary.
+
+ Uses OrderedDict to sort a dictionary.
+
+ Args:
+ dictionary -> the dictionary to sort.
+
+ Returns:
+ Returns the dictionary, but sorted.
+
+ """
+ ret = dict(OrderedDict(sorted(dictionary.items())))
+ logger.debug(
+ f"The old dictionary was {dictionary} and I am sorting it to {ret}"
+ )
+ return ret
+
===========changed ref 9===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def is_ascii(s: str) -> bool:
+ """Returns the boolean value if is_ascii is an ascii char.
+
+ Does what it says on the tree. Stolen from
+ https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii
+
+ Args:
+ s -> the char to check.
+
+ Returns:
+ Returns the boolean of the char.
+
+ """
+
+ return bool(lambda s: len(s) == len(s.encode()))
+
===========changed ref 10===========
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def gcd(a, b) -> int:
- def gcd(self, a, b):
+ """Greatest common divisor.
+
+ The Greatest Common Divisor of a and b using Euclid's Algorithm.
- # Return the Greatest Common Divisor of a and b using Euclid's Algorithm
+
+ Args:
+ a -> num 1
+ b -> num 2
+
+ Returns:
+ Returns GCD(a, b)
+
+ """
+ # Return
while a != 0:
a, b = b % a, a
return b
===========changed ref 11===========
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def percentage(part: float, whole: float) -> float:
- def percentage(self, part, whole):
+ """Returns percentage.
+
+ Just a normal algorithm to return the percent.
+
+ Args:
+ part -> part of the whole number
+ whole -> the whole number
+
+ Returns:
+ Returns the percentage of part to whole.
+
+ """
- """Works with percentages"""
- # yeah uhm sometimes I'm a dummy dum dum and I think dividing by 0 is a good idea
- # this if statememt is to stop my stupidity
if part <= 0 or whole <= 0:
return 0
# works with percentages
return 100 * float(part) / float(whole)
===========changed ref 12===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def newSort(self, newDict):
- # gets the key of the dictionary
- # keyDict = list(newDict.keys())[0]
- # gets the items of that key (which is a dictionary)
- d = dict(newDict)
-
- # (f"d is {d}")
- logger.debug(f"The old dictionary before newSort() is {newDict}")
- sortedI = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
- logger.debug(f"The dictionary after newSort() is {sortedI}")
- # sortedI = sortDictionary(x)
- return sortedI
-
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.cleanText
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<2>:<add> text = self.mh.strip_puncuation(text)
<del> text = self.mh.stripPuncuation(text)
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def cleanText(self, text):
<0> # makes the text unique words and readable
<1> text = text.lower()
<2> text = self.mh.stripPuncuation(text)
<3> text = text.split(" ")
<4> text = list(set(text))
<5> return text
<6>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.__init__
self.mh = mh.mathsHelper()
at: mathsHelper.mathsHelper
strip_puncuation(text: str) -> str
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def getItemAtIndexZero(self, items):
- return items[0]
-
===========changed ref 1===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def get_item_at_index_zero(items):
+ """Gets the item at index 0 from an iterable"""
+ return items[0]
+
===========changed ref 2===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def stripPuncuation(self, text):
- """Strips punctuation from a given string"""
- text = str(text).translate(str.maketrans("", "", punctuation))
- return text
-
===========changed ref 3===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def checkEqual(self, a):
- """checks if all items in an iterable are the same
- https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical"""
- return a.count(a[0]) == len(a)
-
===========changed ref 4===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def sortDictionary(self, dictionary):
- """Sorts a dictionary"""
- ret = dict(OrderedDict(sorted(dictionary.items())))
- logger.debug(
- f"The old dictionary was {dictionary} and I am sorting it to {ret}"
- )
- return ret
-
===========changed ref 5===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def isAscii(self, letter):
- """Determines whether a letter (or word) is ASCII"""
- # checks if a charecter is ascii
- # https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii
- return bool(lambda s: len(s) == len(s.encode()))
-
===========changed ref 6===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def strip_puncuation(text: str) -> str:
+ """Strips punctuation from a given string.
+
+ Uses string.puncuation.
+
+ Args:
+ text -> the text to strip puncuation from.
+
+ Returns:
+ Returns string without puncuation.
+
+ """
+ text: str = str(text).translate(str.maketrans("", "", punctuation))
+ return text
+
===========changed ref 7===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def check_equal(a) -> bool:
+ """checks if all items in an iterable are the same.
+
+ https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical
+
+ Args:
+ a -> an iterable
+
+ Returns:
+ Returns boolean.
+
+ """
+ return a.count(a[0]) == len(a)
+
===========changed ref 8===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def sort_dictionary(dictionary: dict) -> dict:
+ """Sorts a dictionary.
+
+ Uses OrderedDict to sort a dictionary.
+
+ Args:
+ dictionary -> the dictionary to sort.
+
+ Returns:
+ Returns the dictionary, but sorted.
+
+ """
+ ret = dict(OrderedDict(sorted(dictionary.items())))
+ logger.debug(
+ f"The old dictionary was {dictionary} and I am sorting it to {ret}"
+ )
+ return ret
+
===========changed ref 9===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def is_ascii(s: str) -> bool:
+ """Returns the boolean value if is_ascii is an ascii char.
+
+ Does what it says on the tree. Stolen from
+ https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii
+
+ Args:
+ s -> the char to check.
+
+ Returns:
+ Returns the boolean of the char.
+
+ """
+
+ return bool(lambda s: len(s) == len(s.encode()))
+
===========changed ref 10===========
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def gcd(a, b) -> int:
- def gcd(self, a, b):
+ """Greatest common divisor.
+
+ The Greatest Common Divisor of a and b using Euclid's Algorithm.
- # Return the Greatest Common Divisor of a and b using Euclid's Algorithm
+
+ Args:
+ a -> num 1
+ b -> num 2
+
+ Returns:
+ Returns GCD(a, b)
+
+ """
+ # Return
while a != 0:
a, b = b % a, a
return b
===========changed ref 11===========
# module: ciphey.mathsHelper
class mathsHelper:
+ @staticmethod
+ def percentage(part: float, whole: float) -> float:
- def percentage(self, part, whole):
+ """Returns percentage.
+
+ Just a normal algorithm to return the percent.
+
+ Args:
+ part -> part of the whole number
+ whole -> the whole number
+
+ Returns:
+ Returns the percentage of part to whole.
+
+ """
- """Works with percentages"""
- # yeah uhm sometimes I'm a dummy dum dum and I think dividing by 0 is a good idea
- # this if statememt is to stop my stupidity
if part <= 0 or whole <= 0:
return 0
# works with percentages
return 100 * float(part) / float(whole)
===========changed ref 12===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def newSort(self, newDict):
- # gets the key of the dictionary
- # keyDict = list(newDict.keys())[0]
- # gets the items of that key (which is a dictionary)
- d = dict(newDict)
-
- # (f"d is {d}")
- logger.debug(f"The old dictionary before newSort() is {newDict}")
- sortedI = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
- logger.debug(f"The dictionary after newSort() is {sortedI}")
- # sortedI = sortDictionary(x)
- return sortedI
-
|
ciphey.neuralNetworkMod.nn/NeuralNetwork.getLetterFreq
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<36>:<add> if letter not in punctuation and self.mh.is_ascii(letter):
<del> if letter not in punctuation and self.mh.isAscii(letter):
|
# module: ciphey.neuralNetworkMod.nn
class NeuralNetwork:
def getLetterFreq(self, text):
<0> # This part creates a letter frequency of the text
<1> letterFreq = {
<2> "a": 0,
<3> "b": 0,
<4> "c": 0,
<5> "d": 0,
<6> "e": 0,
<7> "f": 0,
<8> "g": 0,
<9> "h": 0,
<10> "i": 0,
<11> "j": 0,
<12> "k": 0,
<13> "l": 0,
<14> "m": 0,
<15> "n": 0,
<16> "o": 0,
<17> "p": 0,
<18> "q": 0,
<19> "r": 0,
<20> "s": 0,
<21> "t": 0,
<22> "u": 0,
<23> "v": 0,
<24> "w": 0,
<25> "x": 0,
<26> "y": 0,
<27> "z": 0,
<28> }
<29>
<30> for letter in text.lower():
<31> if letter in letterFreq:
<32> letterFreq[letter] += 1
<33> else:
<34> # if letter is not puncuation, but it is still ascii
<35> # it's probably a different language so add it to the dict
<36> if letter not in punctuation and self.mh.isAscii(letter):
<37> letterFreq[letter] = 1
<38> return list(letterFreq.values())
<39>
|
===========unchanged ref 0===========
at: ciphey.mathsHelper.mathsHelper
is_ascii(s: str) -> bool
at: ciphey.neuralNetworkMod.nn.NeuralNetwork.__init__
self.mh = mh.mathsHelper()
at: string
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
===========changed ref 0===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def is_ascii(s: str) -> bool:
+ """Returns the boolean value if is_ascii is an ascii char.
+
+ Does what it says on the tree. Stolen from
+ https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii
+
+ Args:
+ s -> the char to check.
+
+ Returns:
+ Returns the boolean of the char.
+
+ """
+
+ return bool(lambda s: len(s) == len(s.encode()))
+
===========changed ref 1===========
+ # module: datasets_root.perm2K.dataset_from_projects.pid-44539.repo-3.code.Ciphey~Ciphey
+
+
===========changed ref 2===========
+ # module: tests.test_encoding
+
+
===========changed ref 3===========
+ # module: tests.test_neuralNetwork
+
+
===========changed ref 4===========
+ # module: tests.test_chi_squared
+
+
===========changed ref 5===========
+ # module: noxfile
+
+
===========changed ref 6===========
+ # module: tests.test_encoding
+ logger.remove()
+
===========changed ref 7===========
+ # module: tests.test_neuralNetwork
+ logger.remove()
+
===========changed ref 8===========
+ # module: tests.test_chi_squared
+ logger.remove()
+
===========changed ref 9===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def getItemAtIndexZero(self, items):
- return items[0]
-
===========changed ref 10===========
+ # module: noxfile
+ """
+ The file for Nox
+ """
+
===========changed ref 11===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def get_item_at_index_zero(items):
+ """Gets the item at index 0 from an iterable"""
+ return items[0]
+
===========changed ref 12===========
+ # module: noxfile
+ @nox.session(python=["3.8", "3.7", "3.6"])
+ def tests(session):
+ session.run("poetry", "install", external=True)
+ session.run("pyhon3 -m pytest", "--cov")
+
===========changed ref 13===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def stripPuncuation(self, text):
- """Strips punctuation from a given string"""
- text = str(text).translate(str.maketrans("", "", punctuation))
- return text
-
===========changed ref 14===========
+ # module: tests.test_encoding
+ class TestEncoding(unittest.TestCase):
+ def test_english_yes(self):
+ lc = LanguageChecker.LanguageChecker()
+ ep = EncodingParent(lc)
+ result = ep.decrypt("eW91ciB0ZXh0")
+ self.assertEqual(result["IsPlaintext?"], True)
+
===========changed ref 15===========
+ # module: tests.test_chi_squared
+ class testChi(unittest.TestCase):
+ def tests_english_no_words(self):
+ self.chi = chiSquared()
+ """
+ Tests to see whether a sentene is classified as English or not
+ """
+ result = self.chi.checkChi("!!!!!!!!!!!!!!!!!!!")
+ self.assertEqual(result, True)
+
===========changed ref 16===========
+ # module: tests.test_encoding
+ class TestEncoding(unittest.TestCase):
+ def test_ascii(self):
+ lc = LanguageChecker.LanguageChecker()
+ ep = EncodingParent(lc)
+ a = "68 65 6C 6C 6F 20 64 6F 67"
+ result = ep.decrypt(a)
+ self.assertEqual(result["IsPlaintext?"], True)
+
===========changed ref 17===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def checkEqual(self, a):
- """checks if all items in an iterable are the same
- https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical"""
- return a.count(a[0]) == len(a)
-
===========changed ref 18===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def sortDictionary(self, dictionary):
- """Sorts a dictionary"""
- ret = dict(OrderedDict(sorted(dictionary.items())))
- logger.debug(
- f"The old dictionary was {dictionary} and I am sorting it to {ret}"
- )
- return ret
-
===========changed ref 19===========
+ # module: tests.test_encoding
+ class TestEncoding(unittest.TestCase):
+ def test_base64_spaces_yes(self):
+ lc = LanguageChecker.LanguageChecker()
+ ep = EncodingParent(lc)
+ result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=")
+ self.assertEqual(result["IsPlaintext?"], True)
+
===========changed ref 20===========
+ # module: tests.test_chi_squared
+ class testChi(unittest.TestCase):
+ def test_chi_english_caps(self):
+ self.chi = chiSquared()
+ """
+ Tests to see whether a sentene is classified as English or not
+ """
+ result = self.chi.checkChi("Hello My NaME IS BraNdOnnn And I LOVE You!")
+ self.assertEqual(result, True)
+
===========changed ref 21===========
+ # module: tests.test_encoding
+ class TestEncoding(unittest.TestCase):
+ def test_base32(self):
+ lc = LanguageChecker.LanguageChecker()
+ ep = EncodingParent(lc)
+ a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF"
+ result = ep.decrypt(a)
+ self.assertEqual(result["IsPlaintext?"], True)
+
===========changed ref 22===========
+ # module: tests.test_neuralNetwork
+ class testNeuralNetwork(unittest.TestCase):
+ def test_md5_yes(self):
+ model = NeuralNetwork()
+ result = model.predictnn("5d41402abc4b2a76b9719d911017c592")
+ numpy.set_printoptions(suppress=True)
+ result = numpy.argmax(result)
+ self.assertEqual(result, 1)
+
===========changed ref 23===========
+ # module: tests.test_neuralNetwork
+ class testNeuralNetwork(unittest.TestCase):
+ def test_caesar_yes(self):
+ model = NeuralNetwork()
+ result = model.predictnn("bcpvu up qvu ifs cpplt bxbz, cvu jotufbe tif qvmmfe")
+ numpy.set_printoptions(suppress=True)
+ result = numpy.argmax(result)
+ self.assertEqual(result, 4)
+
===========changed ref 24===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def cleanText(self, text):
# makes the text unique words and readable
text = text.lower()
+ text = self.mh.strip_puncuation(text)
- text = self.mh.stripPuncuation(text)
text = text.split(" ")
text = list(set(text))
return text
|
ciphey.__main__/Ciphey.__init__
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<7>:<add> self.text: str = text
<del> self.text = text
<9>:<del> # the decryptor components
<13>:<add> self.level: int = 1
<del> self.level = 1
<14>:<add> self.sickomode: bool = False
<del> self.sickomode = False
<15>:<add> self.greppable: bool = grep
<del> self.greppable = grep
<18>:<add> self.probability_distribution: dict = {}
<add> self.what_to_choose: dict = {}
|
# module: ciphey.__main__
class Ciphey:
def __init__(self, text, grep=False, cipher=False, debug=False):
<0> if not debug:
<1> logger.remove()
<2> # general purpose modules
<3> self.ai = NeuralNetwork()
<4> self.lc = lc.LanguageChecker()
<5> self.mh = mh.mathsHelper()
<6> # the one bit of text given to us to decrypt
<7> self.text = text
<8> logger.debug(f"The inputted text at __main__ is {self.text}")
<9> # the decryptor components
<10> self.basic = BasicParent(self.lc)
<11> self.hash = HashParent()
<12> self.encoding = EncodingParent(self.lc)
<13> self.level = 1
<14> self.sickomode = False
<15> self.greppable = grep
<16> self.cipher = cipher
<17> self.console = Console()
<18>
|
===========unchanged ref 0===========
at: Decryptor.Encoding.encodingParent
EncodingParent(lc)
at: Decryptor.Hash.hashParent
HashParent()
at: Decryptor.basicEncryption.basic_parent
BasicParent(lc)
at: ciphey.Decryptor.Encoding.encodingParent
EncodingParent(lc)
at: ciphey.Decryptor.Hash.hashParent
HashParent()
at: ciphey.Decryptor.basicEncryption.basic_parent
BasicParent(lc)
at: ciphey.neuralNetworkMod.nn
NeuralNetwork()
===========changed ref 0===========
# module: ciphey.__main__
logger.add(
sys.stderr,
format="{time} {level} {message}",
filter="my_module",
level="DEBUG",
diagnose=True,
backtrace=True,
)
warnings.filterwarnings("ignore")
+ # Depending on whether Ciphey is called, or Ciphey/__main__
- # Depening on whether ciphey is called, or ciphey/__main__
# we need different imports to deal with both cases
try:
from languageCheckerMod import LanguageChecker as lc
from neuralNetworkMod.nn import NeuralNetwork
from Decryptor.basicEncryption.basic_parent import BasicParent
from Decryptor.Hash.hashParent import HashParent
from Decryptor.Encoding.encodingParent import EncodingParent
except ModuleNotFoundError:
from ciphey.languageCheckerMod import LanguageChecker as lc
from ciphey.neuralNetworkMod.nn import NeuralNetwork
from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent
from ciphey.Decryptor.Hash.hashParent import HashParent
from ciphey.Decryptor.Encoding.encodingParent import EncodingParent
try:
import mathsHelper as mh
except ModuleNotFoundError:
import ciphey.mathsHelper as mh
===========changed ref 1===========
# module: ciphey.__main__
"""
██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗
██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝
██║ ██║██████╔╝███████║█████╗ ╚████╔╝
██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝
╚██████╗██║█</s>
===========changed ref 2===========
# module: ciphey.__main__
# offset: 1
<s>█████╗██║██║ ██║ ██║███████╗ ██║
© Brandon Skerritt
https://github.com/brandonskerritt/ciphey
+
+ The cycle goes:
+ main -> argparsing (if needed) -> call_encryption -> new Ciphey object -> decrypt() -> produceProbTable -> one_level_of_decryption -> decrypt_normal
+
+ Ciphey can be called 3 ways:
+ echo 'text' | ciphey
+ ciphey 'text'
+ ciphey -t 'text'
+ main captures the first 2
+ argparsing captures the last one (-t)
+ it sends this to call_encryption, which can handle all 3 arguments using dict unpacking
+
+ decrypt() creates the prob table and prints it.
+
+ one_level_of_decryption() allows us to repeatedly call one_level_of_decryption on the inputs
+ so if something is doubly encrypted, we can use this to find it.
+
+ Decrypt_normal is one round of decryption. We need one_level_of_decryption to call it, as one_level_of_decryption handles progress bars and stuff.
"""
===========changed ref 3===========
+ # module: datasets_root.perm2K.dataset_from_projects.pid-44539.repo-3.code.Ciphey~Ciphey
+
+
===========changed ref 4===========
+ # module: tests.test_encoding
+
+
===========changed ref 5===========
+ # module: tests.test_neuralNetwork
+
+
===========changed ref 6===========
+ # module: tests.test_chi_squared
+
+
===========changed ref 7===========
+ # module: noxfile
+
+
===========changed ref 8===========
+ # module: tests.test_encoding
+ logger.remove()
+
===========changed ref 9===========
+ # module: tests.test_neuralNetwork
+ logger.remove()
+
===========changed ref 10===========
+ # module: tests.test_chi_squared
+ logger.remove()
+
===========changed ref 11===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def getItemAtIndexZero(self, items):
- return items[0]
-
===========changed ref 12===========
+ # module: noxfile
+ """
+ The file for Nox
+ """
+
===========changed ref 13===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def get_item_at_index_zero(items):
+ """Gets the item at index 0 from an iterable"""
+ return items[0]
+
===========changed ref 14===========
+ # module: noxfile
+ @nox.session(python=["3.8", "3.7", "3.6"])
+ def tests(session):
+ session.run("poetry", "install", external=True)
+ session.run("pyhon3 -m pytest", "--cov")
+
===========changed ref 15===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def stripPuncuation(self, text):
- """Strips punctuation from a given string"""
- text = str(text).translate(str.maketrans("", "", punctuation))
- return text
-
===========changed ref 16===========
+ # module: tests.test_encoding
+ class TestEncoding(unittest.TestCase):
+ def test_english_yes(self):
+ lc = LanguageChecker.LanguageChecker()
+ ep = EncodingParent(lc)
+ result = ep.decrypt("eW91ciB0ZXh0")
+ self.assertEqual(result["IsPlaintext?"], True)
+
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<0>:<add> print("The decrypt method is called")
<add> """Performs the decryption of text
<add>
<add> Creates the probability table, calls one_level_of_decryption
<add>
<add> Args:
<add> None, it uses class variables.
<add>
<add> Returns:
<add> None
<add> """
<3>:<add>
<add> print(result)
<5>:<add> print(f"Returning {self.text}")
<add> return self.text
<del> return None
<6>:<add> self.probability_distribution: dict = self.ai.predictnn(self.text)[0]
<del> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<7>:<add> self.what_to_choose: dict = {
<del> self.whatToChoose = {
<9>:<add> "sha1": self.probability_distribution[0],
<del> "sha1": self.probabilityDistribution[0],
<10>:<add> "md5": self.probability_distribution[1],
<del> "md5": self.probabilityDistribution[1],
<11>:<add> "sha256": self.probability_distribution[2],
<del> "sha256": self.probabilityDistribution[2],
<12>:<add> "sha512": self.probability_distribution[3],
<del> "sha512": self.probabilityDistribution[3],
<14>:<add> self.basic: {"caesar": self.probability
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> # Read the documentation for more on this function.
<1> # checks to see if inputted text is plaintext
<2> result = self.lc.checkLanguage(self.text)
<3> if result:
<4> print("You inputted plain text!")
<5> return None
<6> self.probabilityDistribution = self.ai.predictnn(self.text)[0]
<7> self.whatToChoose = {
<8> self.hash: {
<9> "sha1": self.probabilityDistribution[0],
<10> "md5": self.probabilityDistribution[1],
<11> "sha256": self.probabilityDistribution[2],
<12> "sha512": self.probabilityDistribution[3],
<13> },
<14> self.basic: {"caesar": self.probabilityDistribution[4]},
<15> "plaintext": {"plaintext": self.probabilityDistribution[5]},
<16> self.encoding: {
<17> "reverse": self.probabilityDistribution[6],
<18> "base64": self.probabilityDistribution[7],
<19> "binary": self.probabilityDistribution[8],
<20> "hexadecimal": self.probabilityDistribution[9],
<21> "ascii": self.probabilityDistribution[10],
<22> "morse": self.probabilityDistribution[11],
<23> },
<24> }
<25>
<26> logger.debug(
<27> f"The probability table before 0.1 in __main__ is {self.whatToChoose}"
<28> )
<29>
<30> # sorts each indiviudal sub-dictionary
<31> for key, value in self.whatToChoose.items():
<32> for k, v in value.items():
<33> # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
<34> if v < 0.01:
<35> self.whatToChoose[key][k] = 0.01
<36> logger.debug(
<37> f"The probability</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
)
self.whatToChoose = self.mh.sortProbTable(self.whatToChoose)
# Creates and prints the probability table
if self.greppable == False:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceProbTable(self.whatToChoose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.whatToChoose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
if self.level <= 1:
self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
return None
===========unchanged ref 0===========
at: Decryptor.Hash.hashParent
HashParent()
at: Decryptor.basicEncryption.basic_parent
BasicParent(lc)
at: ciphey.Decryptor.Encoding.encodingParent
EncodingParent(lc)
at: ciphey.languageCheckerMod.LanguageChecker
LanguageChecker()
at: ciphey.mathsHelper
mathsHelper()
at: languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text)
at: neuralNetworkMod.nn
NeuralNetwork()
at: neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def __init__(self, text, grep=False, cipher=False, debug=False):
if not debug:
logger.remove()
# general purpose modules
self.ai = NeuralNetwork()
self.lc = lc.LanguageChecker()
self.mh = mh.mathsHelper()
# the one bit of text given to us to decrypt
+ self.text: str = text
- self.text = text
logger.debug(f"The inputted text at __main__ is {self.text}")
- # the decryptor components
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
+ self.level: int = 1
- self.level = 1
+ self.sickomode: bool = False
- self.sickomode = False
+ self.greppable: bool = grep
- self.greppable = grep
self.cipher = cipher
self.console = Console()
+ self.probability_distribution: dict = {}
+ self.what_to_choose: dict = {}
===========changed ref 1===========
# module: ciphey.__main__
logger.add(
sys.stderr,
format="{time} {level} {message}",
filter="my_module",
level="DEBUG",
diagnose=True,
backtrace=True,
)
warnings.filterwarnings("ignore")
+ # Depending on whether Ciphey is called, or Ciphey/__main__
- # Depening on whether ciphey is called, or ciphey/__main__
# we need different imports to deal with both cases
try:
from languageCheckerMod import LanguageChecker as lc
from neuralNetworkMod.nn import NeuralNetwork
from Decryptor.basicEncryption.basic_parent import BasicParent
from Decryptor.Hash.hashParent import HashParent
from Decryptor.Encoding.encodingParent import EncodingParent
except ModuleNotFoundError:
from ciphey.languageCheckerMod import LanguageChecker as lc
from ciphey.neuralNetworkMod.nn import NeuralNetwork
from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent
from ciphey.Decryptor.Hash.hashParent import HashParent
from ciphey.Decryptor.Encoding.encodingParent import EncodingParent
try:
import mathsHelper as mh
except ModuleNotFoundError:
import ciphey.mathsHelper as mh
===========changed ref 2===========
# module: ciphey.__main__
"""
██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗
██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝
██║ ██║██████╔╝███████║█████╗ ╚████╔╝
██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝
╚██████╗██║█</s>
|
ciphey.__main__/Ciphey.one_level_of_decryption
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<0>:<add> """Performs one level of encryption.
<add>
<add> Either uses alive_bar or not depending on if self.greppable is set.
<add>
<add> Returns:
<add> None.
<add>
<add> """
<2>:<add> output = None
<4>:<add> output = self.decrypt_normal()
<del> self.decryptNormal()
<7>:<add> output = self.decrypt_normal()
<del> self.decryptNormal()
<8>:<add> print(f"One level returning {output}")
<add> return output
|
# module: ciphey.__main__
class Ciphey:
+ def one_level_of_decryption(self) -> None:
- def one_level_of_decryption(self, file=None, sickomode=None):
<0> # Calls one level of decryption
<1> # mainly used to control the progress bar
<2> if self.greppable:
<3> logger.debug("__main__ is running as greppable")
<4> self.decryptNormal()
<5> else:
<6> logger.debug("__main__ is running with progress bar")
<7> self.decryptNormal()
<8>
|
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def __init__(self, text, grep=False, cipher=False, debug=False):
if not debug:
logger.remove()
# general purpose modules
self.ai = NeuralNetwork()
self.lc = lc.LanguageChecker()
self.mh = mh.mathsHelper()
# the one bit of text given to us to decrypt
+ self.text: str = text
- self.text = text
logger.debug(f"The inputted text at __main__ is {self.text}")
- # the decryptor components
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
+ self.level: int = 1
- self.level = 1
+ self.sickomode: bool = False
- self.sickomode = False
+ self.greppable: bool = grep
- self.greppable = grep
self.cipher = cipher
self.console = Console()
+ self.probability_distribution: dict = {}
+ self.what_to_choose: dict = {}
===========changed ref 1===========
# module: ciphey.__main__
logger.add(
sys.stderr,
format="{time} {level} {message}",
filter="my_module",
level="DEBUG",
diagnose=True,
backtrace=True,
)
warnings.filterwarnings("ignore")
+ # Depending on whether Ciphey is called, or Ciphey/__main__
- # Depening on whether ciphey is called, or ciphey/__main__
# we need different imports to deal with both cases
try:
from languageCheckerMod import LanguageChecker as lc
from neuralNetworkMod.nn import NeuralNetwork
from Decryptor.basicEncryption.basic_parent import BasicParent
from Decryptor.Hash.hashParent import HashParent
from Decryptor.Encoding.encodingParent import EncodingParent
except ModuleNotFoundError:
from ciphey.languageCheckerMod import LanguageChecker as lc
from ciphey.neuralNetworkMod.nn import NeuralNetwork
from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent
from ciphey.Decryptor.Hash.hashParent import HashParent
from ciphey.Decryptor.Encoding.encodingParent import EncodingParent
try:
import mathsHelper as mh
except ModuleNotFoundError:
import ciphey.mathsHelper as mh
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
-
- def produceProbTable(self, probTable):
- """Produces the probability table using Rich's API
-
- :probTable: the probability distribution table returned by the neural network
- :returns: Nothing, it prints out the prob table.
-
- """
- logger.debug(f"Producing log table")
- table = Table(show_header=True, header_style="bold magenta")
- table.add_column("Name of Cipher")
- table.add_column("Probability", justify="right")
- # for every key, value in dict add a row
- # I think key is self.caesarcipher and not "caesar cipher"
- # i must callName() somewhere else in this code
- sortedDic = {}
- for k, v in probTable.items():
- for key, value in v.items():
- # Prevents the table from showing pointless 0.01 probs as they're faked
- if value == 0.01:
- continue
- logger.debug(f"Key is {str(key)} and value is {str(value)}")
- valInt = round(self.mh.percentage(value, 1), 2)
- keyStr = str(key).capitalize()
- if "Base" in keyStr:
- keyStr = keyStr[0:-2]
- sortedDic[keyStr] = valInt
- logger.debug(f"The value as percentage is {valInt} and key is {keyStr}")
- sortedDic = {
- k: v
- for k, v in sorted(
- sortedDic.items(), key=lambda item: item[1], reverse=True
- )
- }
- for k, v in sortedDic.items():
- table.add_row(k, str(v) + "%")</s>
===========changed ref 3===========
# module: ciphey.__main__
class Ciphey:
-
- def produceProbTable(self, probTable):
# offset: 1
<s> for k, v in sortedDic.items():
- table.add_row(k, str(v) + "%")
- self.console.print(table)
-
===========changed ref 4===========
# module: ciphey.__main__
class Ciphey:
+
+ def produceprobtable(self, prob_table) -> None:
+ """Produces the probability table using Rich's API
+
+ Uses Rich's API to print the probability table.
+
+ Args:
+ prob_table -> the probability table generated by the neural network
+
+ Returns:
+ None, but prints the probability table.
+
+ """
+ logger.debug(f"Producing log table")
+ table = Table(show_header=True, header_style="bold magenta")
+ table.add_column("Name of Cipher")
+ table.add_column("Probability", justify="right")
+ # for every key, value in dict add a row
+ # I think key is self.caesarcipher and not "caesar cipher"
+ # i must callName() somewhere else in this code
+ sorted_dic: dict = {}
+ for k, v in prob_table.items():
+ for key, value in v.items():
+ # Prevents the table from showing pointless 0.01 probs as they're faked
+ if value == 0.01:
+ continue
+ # gets the string ready to print
+ logger.debug(f"Key is {str(key)} and value is {str(value)}")
+ val: int = round(self.mh.percentage(value, 1), 2)
+ key_str: str = str(key).capitalize()
+ # converts "Base64" to "Base"
+ if "Base" in key_str:
+ key_str = key_str[0:-2]
+ sorted_dic[key_str] = val
+ logger.debug(f"The value as percentage is {val} and key is {key_str}")
+ sorted_dic: dict = {
+ k: v
+ for k, v</s>
===========changed ref 5===========
# module: ciphey.__main__
class Ciphey:
+
+ def produceprobtable(self, prob_table) -> None:
# offset: 1
<s>_str}")
+ sorted_dic: dict = {
+ k: v
+ for k, v in sorted(
+ sorted_dic.items(), key=lambda item: item[1], reverse=True
+ )
+ }
+ for k, v in sorted_dic.items():
+ table.add_row(k, str(v) + "%")
+
+ self.console.print(table)
+ return None
+
|
ciphey.__main__/main
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<0>:<add> """Function to deal with arguments. Either calls with args or not. Makes Pytest work.
<add> Returns:
<add> The output of the decryption.
<add> """
<add> # testing is if we run pytest
<add> result = locals()
<add> if withArgs:
<add> result.update(arg_parsing())
<add> result.pop("withArgs")
<1>:<del> parser = argparse.ArgumentParser(
<2>:<del> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<3>:<del> Examples:
<4>:<del> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<5>:<del> """
<6>:<del> )
<7>:<del> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<8>:<del> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<9>:<del> parser.add_argument(
<10>:<del> "-g",
<11>:<del> "--greppable",
<12>:<del> help="Only output the answer, no progress bars or information. Useful for grep",
<13>:<del> action="store_true",
<14>:<del> required=False,
<15>:<del> )
<16>:<del> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<17>:<del> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<18>:<del> parser.add_argument(
<19>:<del> "-c",
<20>:<del> "--printcipher",
<21>:<del> help="Do you want information on the cipher used?",
<22>:<del> action="store_true",
<23>:<del> required=False,
<24>:<del> )
<25>:<del> # fake argument to stop argparser complaining about no arguments
<26>:<del> # allows sys.argv to be used
<27>:<del> parser.add_argument("-m", action="store_false", default=True, required=False)
<28>:<del>
<29>:<del> parser.add_argument(
<30>:<del> "-d",
<31>:<del> "--debug",
<32>:<del> help="Activates debug mode",
<33>:<del> required=False,
<34>:<del>
|
# module: ciphey.__main__
+ def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict:
- def main():
<0>
<1> parser = argparse.ArgumentParser(
<2> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<3> Examples:
<4> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<5> """
<6> )
<7> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<8> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<9> parser.add_argument(
<10> "-g",
<11> "--greppable",
<12> help="Only output the answer, no progress bars or information. Useful for grep",
<13> action="store_true",
<14> required=False,
<15> )
<16> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<17> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<18> parser.add_argument(
<19> "-c",
<20> "--printcipher",
<21> help="Do you want information on the cipher used?",
<22> action="store_true",
<23> required=False,
<24> )
<25> # fake argument to stop argparser complaining about no arguments
<26> # allows sys.argv to be used
<27> parser.add_argument("-m", action="store_false", default=True, required=False)
<28>
<29> parser.add_argument(
<30> "-d",
<31> "--debug",
<32> help="Activates debug mode",
<33> required=False,
<34> </s>
|
===========below chunk 0===========
# module: ciphey.__main__
+ def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict:
- def main():
# offset: 1
)
parser.add_argument("rest", nargs=argparse.REMAINDER)
args = vars(parser.parse_args())
if args["printcipher"]:
cipher = True
else:
cipher = False
if args["greppable"]:
greppable = True
else:
greppable = False
if args["debug"]:
debug = True
else:
debug = False
text = None
# the below text does:
# if -t is supplied, use that
# if ciphey is called like:
# ciphey 'encrypted text' use that
# else if data is piped like:
# echo 'hello' | ciphey use that
# if no data is supplied, no arguments supplied.
if args["text"]:
text = args["text"]
if args["text"] == None and len(sys.argv) > 1:
text = args["rest"][0]
if not sys.stdin.isatty():
text = str(sys.stdin.read())
if len(sys.argv) == 1 and text == None:
print("No arguments were supplied. Look at the help menu with -h or --help")
if text != None:
cipherObj = Ciphey(text, greppable, cipher, debug)
cipherObj.decrypt()
else:
print("You did not input any text")
===========unchanged ref 0===========
at: argparse
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: ciphey.__main__.Ciphey.__init__
self.text: str = text
self.greppable: bool = grep
self.cipher = cipher
self.what_to_choose: dict = {}
at: ciphey.__main__.Ciphey.decrypt
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
+ def one_level_of_decryption(self) -> None:
- def one_level_of_decryption(self, file=None, sickomode=None):
+ """Performs one level of encryption.
+
+ Either uses alive_bar or not depending on if self.greppable is set.
+
+ Returns:
+ None.
+
+ """
# Calls one level of decryption
# mainly used to control the progress bar
+ output = None
if self.greppable:
logger.debug("__main__ is running as greppable")
+ output = self.decrypt_normal()
- self.decryptNormal()
else:
logger.debug("__main__ is running with progress bar")
+ output = self.decrypt_normal()
- self.decryptNormal()
+ print(f"One level returning {output}")
+ return output
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def __init__(self, text, grep=False, cipher=False, debug=False):
if not debug:
logger.remove()
# general purpose modules
self.ai = NeuralNetwork()
self.lc = lc.LanguageChecker()
self.mh = mh.mathsHelper()
# the one bit of text given to us to decrypt
+ self.text: str = text
- self.text = text
logger.debug(f"The inputted text at __main__ is {self.text}")
- # the decryptor components
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
+ self.level: int = 1
- self.level = 1
+ self.sickomode: bool = False
- self.sickomode = False
+ self.greppable: bool = grep
- self.greppable = grep
self.cipher = cipher
self.console = Console()
+ self.probability_distribution: dict = {}
+ self.what_to_choose: dict = {}
===========changed ref 2===========
# module: ciphey.__main__
logger.add(
sys.stderr,
format="{time} {level} {message}",
filter="my_module",
level="DEBUG",
diagnose=True,
backtrace=True,
)
warnings.filterwarnings("ignore")
+ # Depending on whether Ciphey is called, or Ciphey/__main__
- # Depening on whether ciphey is called, or ciphey/__main__
# we need different imports to deal with both cases
try:
from languageCheckerMod import LanguageChecker as lc
from neuralNetworkMod.nn import NeuralNetwork
from Decryptor.basicEncryption.basic_parent import BasicParent
from Decryptor.Hash.hashParent import HashParent
from Decryptor.Encoding.encodingParent import EncodingParent
except ModuleNotFoundError:
from ciphey.languageCheckerMod import LanguageChecker as lc
from ciphey.neuralNetworkMod.nn import NeuralNetwork
from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent
from ciphey.Decryptor.Hash.hashParent import HashParent
from ciphey.Decryptor.Encoding.encodingParent import EncodingParent
try:
import mathsHelper as mh
except ModuleNotFoundError:
import ciphey.mathsHelper as mh
|
ciphey.Decryptor.basicEncryption.affine/Affine.decryptMessage
|
Modified
|
Ciphey~Ciphey
|
99d33b928dab46cf0d96846130b021c77c0f193a
|
Merge remote-tracking branch 'origin/master' into switchPoetry
|
<3>:<add> modInverseOfKeyA = self.mh.find_mod_inverse(keyA, len(SYMBOLS))
<del> modInverseOfKeyA = self.mh.findModInverse(keyA, len(SYMBOLS))
|
# module: ciphey.Decryptor.basicEncryption.affine
class Affine:
def decryptMessage(self, key, message):
<0> keyA, keyB = getKeyParts(key)
<1> self.checkKeys(keyA, keyB, "decrypt")
<2> plaintext = ""
<3> modInverseOfKeyA = self.mh.findModInverse(keyA, len(SYMBOLS))
<4>
<5> for symbol in message:
<6> if symbol in self.SYMBOLS:
<7> # Decrypt the symbol:
<8> symbolIndex = self.SYMBOLS.find(symbol)
<9> plaintext += self.SYMBOLS[
<10> (symbolIndex - keyB) * modInverseOfKeyA % len(self.SYMBOLS)
<11> ]
<12> else:
<13> plaintext += symbol # Append the symbol without decrypting.
<14> return plaintext
<15>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.basicEncryption.affine.Affine
checkKeys(keyA, keyB, mode)
at: ciphey.Decryptor.basicEncryption.affine.Affine.__init__
self.mh = mathsHelper()
self.SYMBOLS = (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?."
)
at: mathsHelper.mathsHelper
find_mod_inverse(a: int, m: int) -> int
===========changed ref 0===========
+ # module: tests.test_integration
+
+
===========changed ref 1===========
+ # module: tests.test_main
+
+
===========changed ref 2===========
+ # module: tests.test_dictionary
+
+
===========changed ref 3===========
+ # module: tests
+
+
===========changed ref 4===========
+ # module: datasets_root.perm2K.dataset_from_projects.pid-44539.repo-3.code.Ciphey~Ciphey
+
+
===========changed ref 5===========
+ # module: tests.test_encoding
+
+
===========changed ref 6===========
+ # module: tests.test_neuralNetwork
+
+
===========changed ref 7===========
+ # module: tests.test_chi_squared
+
+
===========changed ref 8===========
+ # module: noxfile
+
+
===========changed ref 9===========
+ # module: tests.test_integration
+ logger.remove()
+
===========changed ref 10===========
+ # module: tests.test_dictionary
+ logger.remove()
+
===========changed ref 11===========
+ # module: tests.test_encoding
+ logger.remove()
+
===========changed ref 12===========
+ # module: tests.test_neuralNetwork
+ logger.remove()
+
===========changed ref 13===========
+ # module: tests.test_chi_squared
+ logger.remove()
+
===========changed ref 14===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def getItemAtIndexZero(self, items):
- return items[0]
-
===========changed ref 15===========
+ # module: noxfile
+ """
+ The file for Nox
+ """
+
===========changed ref 16===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ """
+ tests integration between chi squared and dictionary checker
+ """
+
===========changed ref 17===========
# module: ciphey.mathsHelper
class mathsHelper:
+
+ @staticmethod
+ def get_item_at_index_zero(items):
+ """Gets the item at index 0 from an iterable"""
+ return items[0]
+
===========changed ref 18===========
+ # module: tests.test_main
+ def test_argument_grep_true():
+ result = main(text="hello")
+ print(result)
+ assert result["Plaintext"] == "hello"
+
===========changed ref 19===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_three(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage("")
+ self.assertEqual(result, False)
+
===========changed ref 20===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_6(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage('"')
+ self.assertEqual(result, False)
+
===========changed ref 21===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_five(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage("#")
+ self.assertEqual(result, False)
+
===========changed ref 22===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_four(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage(".")
+ self.assertEqual(result, False)
+
===========changed ref 23===========
+ # module: noxfile
+ @nox.session(python=["3.8", "3.7", "3.6"])
+ def tests(session):
+ session.run("poetry", "install", external=True)
+ session.run("pyhon3 -m pytest", "--cov")
+
===========changed ref 24===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_basics_german(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage("hallo keine lieben leute nach")
+ self.assertEqual(result, False)
+
===========changed ref 25===========
# module: ciphey.mathsHelper
class mathsHelper:
-
- def stripPuncuation(self, text):
- """Strips punctuation from a given string"""
- text = str(text).translate(str.maketrans("", "", punctuation))
- return text
-
===========changed ref 26===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_one(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage("HELLO MY NAME IS BRANDON AND I LIKE DOLLAR")
+ self.assertEqual(result, True)
+
===========changed ref 27===========
+ # module: tests.test_dictionary
+ class testDictionary(unittest.TestCase):
+ def test_english_false(self):
+ dc = dictionaryChecker()
+ result = dc.confirmlanguage("jdajj kop9u0r 9jjidasjp", "English")
+ self.assertEqual(result, False)
+
===========changed ref 28===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_basics(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage(
+ "Hello my name is new and this is an example of some english text"
+ )
+ self.assertEqual(result, True)
+
===========changed ref 29===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_two(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
+ self.assertEqual(result, False)
+
===========changed ref 30===========
# module: ciphey.__main__
if __name__ == "__main__":
+ # withArgs because this function is only called
+ # if the program is run in terminal
+ main(withArgs=True)
- main()
===========changed ref 31===========
+ # module: tests.test_dictionary
+ class testDictionary(unittest.TestCase):
+ def test_english_yes(self):
+ dc = dictionaryChecker()
+ result = dc.confirmlanguage(
+ "hello again my friend this is my name and I like dogs!", "English"
+ )
+ self.assertEqual(result, True)
+
===========changed ref 32===========
+ # module: tests.test_encoding
+ class TestEncoding(unittest.TestCase):
+ def test_english_yes(self):
+ lc = LanguageChecker.LanguageChecker()
+ ep = EncodingParent(lc)
+ result = ep.decrypt("eW91ciB0ZXh0")
+ self.assertEqual(result["IsPlaintext?"], True)
+
===========changed ref 33===========
+ # module: tests.test_integration
+ class testIntegration(unittest.TestCase):
+ def test_integration_unusual_7(self):
+ lc = LanguageChecker.LanguageChecker()
+ result = lc.checkLanguage("")
+ self.assertEqual(result, False)
+
===========changed ref 34===========
+ # module: tests.test_chi_squared
+ class testChi(unittest.TestCase):
+ def tests_english_no_words(self):
+ self.chi = chiSquared()
+ """
+ Tests to see whether a sentene is classified as English or not
+ """
+ result = self.chi.checkChi("!!!!!!!!!!!!!!!!!!!")
+ self.assertEqual(result, True)
+
|
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.__add__
|
Modified
|
Ciphey~Ciphey
|
77d6cd85b1aeda3fab22e3970e606d26ecf4d093
|
Merge remote-tracking branch 'origin/master'
|
<0>:<add> """Adds together 2 languageChecker objects
<add>
<add>
<add> Args:
<add> otherLanguageObject -> the other language checker mod
<add>
<add> Returns:
<add> A single languageCheckerObj comprised of 2
<add>
<add> """
|
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
def __add__(self, otherLanguageObject):
<0> # sets the added chi squared to be of this one
<1> new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj()
<2> self.chi = new
<3> return self
<4>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__add__
self.chi = new
at: languageCheckerMod.chisquared
chiSquared()
at: languageCheckerMod.dictionaryChecker
dictionaryChecker()
|
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.checkLanguage
|
Modified
|
Ciphey~Ciphey
|
77d6cd85b1aeda3fab22e3970e606d26ecf4d093
|
Merge remote-tracking branch 'origin/master'
|
<0>:<add> """Checks to see if the text is in English
<add> Uses chisqaured
<add>
<add> Performs a decryption, but mainly parses the internal data packet and prints useful information.
<add>
<add> Args:
<add> text -> The text we use to perform analysis on
<add>
<add> Returns:
<add> bool -> True if the text is English, False otherwise.
<add>
<add> """
<3>:<add> result: bool = self.chi.checkChi(text)
<del> result = self.chi.checkChi(text)
<17>:<add> result2: bool = self.dictionary.confirmlanguage(text, "english")
<del> result2 = self.dictionary.confirmlanguage(text, "english")
|
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
+ def checkLanguage(self, text: str) -> bool:
- def checkLanguage(self, text):
<0> logger.debug(f"In Language Checker with {text}")
<1> if text == "":
<2> return False
<3> result = self.chi.checkChi(text)
<4> if not result:
<5> logger.debug(
<6> f"Chi squared failed. Attempting 1000 words"
<7> )
<8> if not self.dictionary.check1000Words(text):
<9> logger.debug(
<10> f"1000 words failed. This is not plaintext"
<11> )
<12> return False
<13>
<14> logger.debug(
<15> f"Language check phase 1 complete"
<16> )
<17> result2 = self.dictionary.confirmlanguage(text, "english")
<18> logger.debug(f"Result is, dictionary checker, is {result2}")
<19> if not result2:
<20> logger.debug(f"Language check phase 2 returns false")
<21> return False
<22> return True
<23>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker
getChiSquaredObj()
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__init__
self.chi = cs.chiSquared()
===========changed ref 0===========
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
def __add__(self, otherLanguageObject):
+ """Adds together 2 languageChecker objects
+
+
+ Args:
+ otherLanguageObject -> the other language checker mod
+
+ Returns:
+ A single languageCheckerObj comprised of 2
+
+ """
# sets the added chi squared to be of this one
new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj()
self.chi = new
return self
|
ciphey.__main__/Ciphey.decrypt_normal
|
Modified
|
Ciphey~Ciphey
|
77d6cd85b1aeda3fab22e3970e606d26ecf4d093
|
Merge remote-tracking branch 'origin/master'
|
<39>:<add> * If the probability table says 'Caesar Cipher' then it is a normal encryption that \
<del> * If the probability table says 'Caesar Cipher
|
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
<0> """Called by one_level_of_decryption
<1>
<2> Performs a decryption, but mainly parses the internal data packet and prints useful information.
<3>
<4> Args:
<5> bar -> whether or not to use alive_Bar
<6>
<7> Returns:
<8> None, but prints.
<9>
<10> """
<11> for key, val in self.what_to_choose.items():
<12> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
<13> if not isinstance(key, str):
<14> key.setProbTable(val)
<15> ret: dict = key.decrypt(self.text)
<16> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<17> logger.debug(
<18> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<19> )
<20>
<21> if ret["IsPlaintext?"]:
<22> print(ret["Plaintext"])
<23> if self.cipher:
<24> if ret["Extra Information"] is not None:
<25> print(
<26> "The cipher used is",
<27> ret["Cipher"] + ".",
<28> ret["Extra Information"] + ".",
<29> )
<30> else:
<31> print("The cipher used is " + ret["Cipher"] + ".")
<32> print(f"Decryption returning {ret}")
<33> return ret
<34>
<35> logger.debug("No encryption found")
<36> print(
<37> """No encryption found. Here are some tips to help crack the cipher:
<38> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
<39> * If the probability table says 'Caesar Cipher</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
# offset: 1
* If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, and then HashCat to crack the hash.
* The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log file of all attempted decryptions and manually search it."""
)
return None
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.text: str = text
self.cipher = cipher
self.what_to_choose: dict = {}
at: ciphey.__main__.Ciphey.decrypt
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
at: ciphey.__main__.Ciphey.one_level_of_decryption
output = self.decrypt_normal()
output = None
===========changed ref 0===========
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
def __add__(self, otherLanguageObject):
+ """Adds together 2 languageChecker objects
+
+
+ Args:
+ otherLanguageObject -> the other language checker mod
+
+ Returns:
+ A single languageCheckerObj comprised of 2
+
+ """
# sets the added chi squared to be of this one
new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj()
self.chi = new
return self
===========changed ref 1===========
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
+ def checkLanguage(self, text: str) -> bool:
- def checkLanguage(self, text):
+ """Checks to see if the text is in English
+ Uses chisqaured
+
+ Performs a decryption, but mainly parses the internal data packet and prints useful information.
+
+ Args:
+ text -> The text we use to perform analysis on
+
+ Returns:
+ bool -> True if the text is English, False otherwise.
+
+ """
logger.debug(f"In Language Checker with {text}")
if text == "":
return False
+ result: bool = self.chi.checkChi(text)
- result = self.chi.checkChi(text)
if not result:
logger.debug(
f"Chi squared failed. Attempting 1000 words"
)
if not self.dictionary.check1000Words(text):
logger.debug(
f"1000 words failed. This is not plaintext"
)
return False
logger.debug(
f"Language check phase 1 complete"
)
+ result2: bool = self.dictionary.confirmlanguage(text, "english")
- result2 = self.dictionary.confirmlanguage(text, "english")
logger.debug(f"Result is, dictionary checker, is {result2}")
if not result2:
logger.debug(f"Language check phase 2 returns false")
return False
return True
|
ciphey.__main__/arg_parsing
|
Modified
|
Ciphey~Ciphey
|
77d6cd85b1aeda3fab22e3970e606d26ecf4d093
|
Merge remote-tracking branch 'origin/master'
|
<14>:<add> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels,
<del> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<15>:<add> # the slower it is)'
<add> # required=False)
|
# module: ciphey.__main__
def arg_parsing() -> dict:
<0> """This function parses arguments.
<1>
<2> Args:
<3> None
<4> Returns:
<5> A tuple containing the arguments, which is unpacked in main()
<6> """
<7> parser = argparse.ArgumentParser(
<8> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n
<9> Examples:
<10> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true
<11> """
<12> )
<13> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False)
<14> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, the slower it is)', required=False)
<15> parser.add_argument(
<16> "-g",
<17> "--greppable",
<18> help="Only output the answer, no progress bars or information. Useful for grep",
<19> action="store_true",
<20> required=False,
<21> )
<22> parser.add_argument("-t", "--text", help="Text to decrypt", required=False)
<23> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False)
<24> parser.add_argument(
<25> "-c",
<26> "--cipher",
<27> help="Do you want information on the cipher used?",
<28> action="store_true",
<29> required=False,
<30> )
<31> # fake argument to stop argparser complaining about no arguments
<32> # allows sys.argv to be used
<33> # parser.add_argument("-m", action="store_false", default=True, required=False)
<34>
<35> parser.add_argument(
<36> "-d",
<37> "--debug",
</s>
|
===========below chunk 0===========
# module: ciphey.__main__
def arg_parsing() -> dict:
# offset: 1
required=False,
action="store_true",
)
parser.add_argument("rest", nargs=argparse.REMAINDER)
args = vars(parser.parse_args())
# the below text does:
# if -t is supplied, use that
# if ciphey is called like:
# ciphey 'encrypted text' use that
# else if data is piped like:
# echo 'hello' | ciphey use that
# if no data is supplied, no arguments supplied.
text = None
if args["text"]:
text = args["text"]
if args["text"] is None and len(sys.argv) > 1:
text = args["rest"][0]
if not sys.stdin.isatty():
text = str(sys.stdin.read())
if len(sys.argv) == 1 and text == None:
print("No arguments were supplied. Look at the help menu with -h or --help")
args["text"] = text
if not args["rest"]:
args.pop("rest")
return args
===========unchanged ref 0===========
at: argparse
REMAINDER = '...'
ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...)
at: argparse.ArgumentParser
parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]]=...) -> Namespace
parse_args(*, namespace: None) -> Namespace
parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N
parse_args(*, namespace: _N) -> _N
at: argparse._ActionsContainer
add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action
at: sys
argv: List[str]
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
"""Called by one_level_of_decryption
Performs a decryption, but mainly parses the internal data packet and prints useful information.
Args:
bar -> whether or not to use alive_Bar
Returns:
None, but prints.
"""
for key, val in self.what_to_choose.items():
# https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
if not isinstance(key, str):
key.setProbTable(val)
ret: dict = key.decrypt(self.text)
logger.debug(f"Decrypt normal in __main__ ret is {ret}")
logger.debug(
f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
)
if ret["IsPlaintext?"]:
print(ret["Plaintext"])
if self.cipher:
if ret["Extra Information"] is not None:
print(
"The cipher used is",
ret["Cipher"] + ".",
ret["Extra Information"] + ".",
)
else:
print("The cipher used is " + ret["Cipher"] + ".")
print(f"Decryption returning {ret}")
return ret
logger.debug("No encryption found")
print(
"""No encryption found. Here are some tips to help crack the cipher:
* Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
+ * If the probability table says 'Caesar Cipher' then it is a normal encryption that \
- * If the probability table says 'Caesar Cipher' then it is a normal encryption that Ciphey cannot decrypt yet.</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
# offset: 1
<s>
- * If the probability table says 'Caesar Cipher' then it is a normal encryption that Ciphey cannot decrypt yet.
+ Ciphey cannot decrypt yet.
+ * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \
- * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, and then HashCat to crack the hash.
+ and then HashCat to crack the hash.
+ * The encryption may not contain normal English plaintext. It could be coordinates or \
+ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \
+ file of all attempted decryptions and manually search it."""
- * The encryption may not contain normal English plaintext. It could be coordinates or another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log file of all attempted decryptions and manually search it."""
)
return None
===========changed ref 2===========
# module: ciphey.languageCheckerMod.LanguageChecker
class LanguageChecker:
def __add__(self, otherLanguageObject):
+ """Adds together 2 languageChecker objects
+
+
+ Args:
+ otherLanguageObject -> the other language checker mod
+
+ Returns:
+ A single languageCheckerObj comprised of 2
+
+ """
# sets the added chi squared to be of this one
new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj()
self.chi = new
return self
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.__init__
|
Modified
|
Ciphey~Ciphey
|
2ba17cc02a7f672f030ca7fbbae43eb16987db88
|
PEP8'd languageChecker
|
<1>:<add> self.languagePercentage: float = 0.0
<del> self.languagePercentage = 0.0
<2>:<add> self.languageWordsCounter: float = 0.0
<del> self.languageWordsCounter = 0.0
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
<0> self.mh = mh.mathsHelper()
<1> self.languagePercentage = 0.0
<2> self.languageWordsCounter = 0.0
<3> self.languageThreshold = 55
<4> # this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
<5> # dictionary because lookup is O(1)
<6> self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
<7>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.checkDictionary
self.languageWordsCounter = counter
self.languagePercentage = self.mh.percentage(
float(self.languageWordsCounter), float(len(text))
)
at: mathsHelper
mathsHelper()
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.cleanText
|
Modified
|
Ciphey~Ciphey
|
2ba17cc02a7f672f030ca7fbbae43eb16987db88
|
PEP8'd languageChecker
|
<0>:<add> """Cleans the texy ready to be checked
<add>
<add> Strips punucation, makes it lower case, turns it into a list seperated by spaces, remvoes duplicate words
<add>
<add> Args:
<add> text -> The text we use to perform analysis on
<add>
<add> Returns:
<add> text -> the text as a list, now cleaned
<add>
<add> """
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def cleanText(self, text: str) -> list:
- def cleanText(self, text):
<0> # makes the text unique words and readable
<1> text = text.lower()
<2> text = self.mh.strip_puncuation(text)
<3> text = text.split(" ")
<4> text = list(set(text))
<5> return text
<6>
|
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
self.mh = mh.mathsHelper()
+ self.languagePercentage: float = 0.0
- self.languagePercentage = 0.0
+ self.languageWordsCounter: float = 0.0
- self.languageWordsCounter = 0.0
self.languageThreshold = 55
# this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
# dictionary because lookup is O(1)
self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.check1000Words
|
Modified
|
Ciphey~Ciphey
|
2ba17cc02a7f672f030ca7fbbae43eb16987db88
|
PEP8'd languageChecker
|
<0>:<add> """Checks to see if word is in the list of 1000 words
<add>
<add> the 1000words is a dict, so lookup is O(1)
<add>
<add> Args:
<add> text -> The text we use to text (a word)
<add>
<add> Returns:
<add> bool -> whether it's in the dict or not.
<add>
<add> """
<4>:<add> text: str = self.cleanText(text)
<del> text = self.cleanText(text)
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def check1000Words(self, text: str) -> bool:
- def check1000Words(self, text):
<0> if text is None:
<1> return False
<2> check = dict.fromkeys(self.top1000Words)
<3> logger.debug(f"text before cleaning is {text}")
<4> text = self.cleanText(text)
<5> logger.debug(f"Check 1000 words text is {text}")
<6> # If any of the top 1000 words in the text appear
<7> # return true
<8> for word in text:
<9> logger.debug(f"Word in check1000 is {word}")
<10> # I was debating using any() here, but I think they're the
<11> # same speed so it doesn't really matter too much
<12> if word in check:
<13> logger.debug(f"Check 1000 words returns True for word {word}")
<14> return True
<15> return False
<16>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.__init__
self.mh = mh.mathsHelper()
at: mathsHelper.mathsHelper
strip_puncuation(text: str) -> str
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
self.mh = mh.mathsHelper()
+ self.languagePercentage: float = 0.0
- self.languagePercentage = 0.0
+ self.languageWordsCounter: float = 0.0
- self.languageWordsCounter = 0.0
self.languageThreshold = 55
# this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
# dictionary because lookup is O(1)
self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
===========changed ref 1===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def cleanText(self, text: str) -> list:
- def cleanText(self, text):
+ """Cleans the texy ready to be checked
+
+ Strips punucation, makes it lower case, turns it into a list seperated by spaces, remvoes duplicate words
+
+ Args:
+ text -> The text we use to perform analysis on
+
+ Returns:
+ text -> the text as a list, now cleaned
+
+ """
# makes the text unique words and readable
text = text.lower()
text = self.mh.strip_puncuation(text)
text = text.split(" ")
text = list(set(text))
return text
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.checkDictionary
|
Modified
|
Ciphey~Ciphey
|
2ba17cc02a7f672f030ca7fbbae43eb16987db88
|
PEP8'd languageChecker
|
<0>:<add> """Sorts & searches the dict
<add>
<add> ompares a word with
<del> """Compares a word with
<1>:<add> The dictionary is sorted and the text is sorted
<del> The dictionary is sorted and the text is sorted"""
<2>:<add> for every single word in main dictionary
<add> if that word == text[0] then +1 to counter
<add> then +1 to text[0 + i]
<add> so say the dict is ordered
<add> we just loop through dict
<add> and eventually we'll reach a point where word in dict = word in text
<add> at that point, we move to the next text point
<add> both text and dict are sorted
<add> so we only loop once, we can do this in O(n log n) time
<add>
<add> Args:
<add> text -> The text we use to perform analysis on
<add> language -> the language we want to check
<add>
<add> Returns:
<add> counter -> how many words in text, are in the dict of language
<add>
<add> """
<4>:<add> text: str = self.cleanText(text)
<del> text = self.cleanText(text)
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def checkDictionary(self, text: str, language: str) -> int:
- def checkDictionary(self, text, language):
<0> """Compares a word with
<1> The dictionary is sorted and the text is sorted"""
<2> # reads through most common words / passwords
<3> # and calculates how much of that is in language
<4> text = self.cleanText(text)
<5> text.sort()
<6>
<7> f = cipheydists.get_list(language)
<8>
<9> # so this should loop until it gets to the point in the @staticmethod
<10> # that equals the word :)
<11>
<12> """
<13> for every single word in main dictionary
<14> if that word == text[0] then +1 to counter
<15> then +1 to text[0 + i]
<16> so say the dict is ordered
<17> we just loop through dict
<18> and eventually we'll reach a point where word in dict = word in text
<19> at that point, we move to the next text point
<20> both text and dict are sorted
<21> so we only loop once, we can do this in O(n log n) time
<22> """
<23> counter = 0
<24> counter_percent = 0
<25>
<26> for dictLengthCounter, word in enumerate(f):
<27> # if there is more words counted than there is text
<28> # it is 100%, sometimes it goes over
<29> # so this stops that
<30> if counter >= len(text):
<31> break
<32> # if the dictionary word is contained in the text somewhere
<33> # counter + 1
<34> if word in text:
<35> counter = counter + 1
<36> counter_percent = counter_percent + 1
<37> self.languageWordsCounter = counter
<38> self.languagePercentage = self.mh.percentage(
<39> float(self.languageWordsCounter), float(len(text))
<40> </s>
|
===========below chunk 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def checkDictionary(self, text: str, language: str) -> int:
- def checkDictionary(self, text, language):
# offset: 1
return counter
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
cleanText(text: str) -> list
cleanText(self, text: str) -> list
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker.__init__
self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def cleanText(self, text: str) -> list:
- def cleanText(self, text):
+ """Cleans the texy ready to be checked
+
+ Strips punucation, makes it lower case, turns it into a list seperated by spaces, remvoes duplicate words
+
+ Args:
+ text -> The text we use to perform analysis on
+
+ Returns:
+ text -> the text as a list, now cleaned
+
+ """
# makes the text unique words and readable
text = text.lower()
text = self.mh.strip_puncuation(text)
text = text.split(" ")
text = list(set(text))
return text
===========changed ref 1===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
self.mh = mh.mathsHelper()
+ self.languagePercentage: float = 0.0
- self.languagePercentage = 0.0
+ self.languageWordsCounter: float = 0.0
- self.languageWordsCounter = 0.0
self.languageThreshold = 55
# this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
# dictionary because lookup is O(1)
self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
===========changed ref 2===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def check1000Words(self, text: str) -> bool:
- def check1000Words(self, text):
+ """Checks to see if word is in the list of 1000 words
+
+ the 1000words is a dict, so lookup is O(1)
+
+ Args:
+ text -> The text we use to text (a word)
+
+ Returns:
+ bool -> whether it's in the dict or not.
+
+ """
if text is None:
return False
check = dict.fromkeys(self.top1000Words)
logger.debug(f"text before cleaning is {text}")
+ text: str = self.cleanText(text)
- text = self.cleanText(text)
logger.debug(f"Check 1000 words text is {text}")
# If any of the top 1000 words in the text appear
# return true
for word in text:
logger.debug(f"Word in check1000 is {word}")
# I was debating using any() here, but I think they're the
# same speed so it doesn't really matter too much
if word in check:
logger.debug(f"Check 1000 words returns True for word {word}")
return True
return False
|
ciphey.languageCheckerMod.dictionaryChecker/dictionaryChecker.confirmlanguage
|
Modified
|
Ciphey~Ciphey
|
2ba17cc02a7f672f030ca7fbbae43eb16987db88
|
PEP8'd languageChecker
|
<0>:<add> """Confirms whether given text is language
<add>
<add> If the languagePercentage (taken from checkDictionary) is higher than the language threshold, reutrn True
<add>
<add> Args:
<add> text -> The text we use to text (a word)
<add> language -> the language we use to check
<add>
<add> Returns:
<add> bool -> whether it's written in Language or not
<add>
<add> """
<1>:<add> if self.languagePercentage >= self.languageThreshold:
<del> if self.languagePercentage > self.languageThreshold:
|
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def confirmlanguage(self, text: str, language: str) -> True:
- def confirmlanguage(self, text, language):
<0> self.checkDictionary(text, language)
<1> if self.languagePercentage > self.languageThreshold:
<2> logger.debug(
<3> f"The language percentange {self.languagePercentage} is over the threshold {self.languageThreshold}"
<4> )
<5> return True
<6> else:
<7> return False
<8>
|
===========unchanged ref 0===========
at: ciphey.languageCheckerMod.dictionaryChecker.dictionaryChecker
cleanText(text: str) -> list
cleanText(self, text: str) -> list
===========changed ref 0===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def cleanText(self, text: str) -> list:
- def cleanText(self, text):
+ """Cleans the texy ready to be checked
+
+ Strips punucation, makes it lower case, turns it into a list seperated by spaces, remvoes duplicate words
+
+ Args:
+ text -> The text we use to perform analysis on
+
+ Returns:
+ text -> the text as a list, now cleaned
+
+ """
# makes the text unique words and readable
text = text.lower()
text = self.mh.strip_puncuation(text)
text = text.split(" ")
text = list(set(text))
return text
===========changed ref 1===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
def __init__(self):
self.mh = mh.mathsHelper()
+ self.languagePercentage: float = 0.0
- self.languagePercentage = 0.0
+ self.languageWordsCounter: float = 0.0
- self.languageWordsCounter = 0.0
self.languageThreshold = 55
# this is hard coded because i dont want to use a library or rely on reading from files, as it's slow.
# dictionary because lookup is O(1)
self.top1000Words = dict.fromkeys(cipheydists.get_list("english1000"))
===========changed ref 2===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def check1000Words(self, text: str) -> bool:
- def check1000Words(self, text):
+ """Checks to see if word is in the list of 1000 words
+
+ the 1000words is a dict, so lookup is O(1)
+
+ Args:
+ text -> The text we use to text (a word)
+
+ Returns:
+ bool -> whether it's in the dict or not.
+
+ """
if text is None:
return False
check = dict.fromkeys(self.top1000Words)
logger.debug(f"text before cleaning is {text}")
+ text: str = self.cleanText(text)
- text = self.cleanText(text)
logger.debug(f"Check 1000 words text is {text}")
# If any of the top 1000 words in the text appear
# return true
for word in text:
logger.debug(f"Word in check1000 is {word}")
# I was debating using any() here, but I think they're the
# same speed so it doesn't really matter too much
if word in check:
logger.debug(f"Check 1000 words returns True for word {word}")
return True
return False
===========changed ref 3===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def checkDictionary(self, text: str, language: str) -> int:
- def checkDictionary(self, text, language):
+ """Sorts & searches the dict
+
+ ompares a word with
- """Compares a word with
+ The dictionary is sorted and the text is sorted
- The dictionary is sorted and the text is sorted"""
+ for every single word in main dictionary
+ if that word == text[0] then +1 to counter
+ then +1 to text[0 + i]
+ so say the dict is ordered
+ we just loop through dict
+ and eventually we'll reach a point where word in dict = word in text
+ at that point, we move to the next text point
+ both text and dict are sorted
+ so we only loop once, we can do this in O(n log n) time
+
+ Args:
+ text -> The text we use to perform analysis on
+ language -> the language we want to check
+
+ Returns:
+ counter -> how many words in text, are in the dict of language
+
+ """
# reads through most common words / passwords
# and calculates how much of that is in language
+ text: str = self.cleanText(text)
- text = self.cleanText(text)
text.sort()
f = cipheydists.get_list(language)
# so this should loop until it gets to the point in the @staticmethod
# that equals the word :)
-
- """
- for every single word in main dictionary
- if that word == text[0] then +1 to counter
- then +1 to text[0 + i]
- so say the dict is ordered
- we just loop through dict
- and eventually we'll reach a point where word in dict = word in text
- </s>
===========changed ref 4===========
# module: ciphey.languageCheckerMod.dictionaryChecker
class dictionaryChecker:
+ def checkDictionary(self, text: str, language: str) -> int:
- def checkDictionary(self, text, language):
# offset: 1
<s>
- we just loop through dict
- and eventually we'll reach a point where word in dict = word in text
- at that point, we move to the next text point
- both text and dict are sorted
- so we only loop once, we can do this in O(n log n) time
- """
+ counter: int = 0
- counter = 0
+ counter_percent: int = 0
- counter_percent = 0
for dictLengthCounter, word in enumerate(f):
# if there is more words counted than there is text
# it is 100%, sometimes it goes over
# so this stops that
if counter >= len(text):
break
# if the dictionary word is contained in the text somewhere
# counter + 1
if word in text:
counter = counter + 1
counter_percent = counter_percent + 1
self.languageWordsCounter = counter
self.languagePercentage = self.mh.percentage(
float(self.languageWordsCounter), float(len(text))
)
return counter
|
ciphey.Decryptor.Encoding.encodingParent/EncodingParent.__init__
|
Modified
|
Ciphey~Ciphey
|
c4b4a667e2228c5bfd0a9dfe4da2c730a68c0fcc
|
Fixing bases & print statements in main
|
<1>:<add> self.base64 = Bases(self.lc)
<del> self.base64 = Base64(self.lc)
|
# module: ciphey.Decryptor.Encoding.encodingParent
class EncodingParent:
def __init__(self, lc):
<0> self.lc = lc
<1> self.base64 = Base64(self.lc)
<2> self.binary = Binary(self.lc)
<3> self.hex = Hexadecimal(self.lc)
<4> self.ascii = Ascii(self.lc)
<5> self.morse = MorseCode(self.lc)
<6>
|
===========unchanged ref 0===========
at: ciphey.Decryptor.Encoding.ascii
Ascii(lc)
at: ciphey.Decryptor.Encoding.bases
Bases(lc)
at: ciphey.Decryptor.Encoding.binary
Binary(lc)
at: ciphey.Decryptor.Encoding.hexadecimal
Hexadecimal(lc)
at: ciphey.Decryptor.Encoding.morsecode
MorseCode(lc)
===========changed ref 0===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+ """
+ turns base64 strings into normal strings
+ """
+
===========changed ref 1===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
===========changed ref 2===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def __init__(self, lc):
+ self.lc = lc
+
===========changed ref 3===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def badRet(self):
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": False,
+ "Plaintext": None,
+ "Cipher": None,
+ "Extra Information": None,
+ }
+
===========changed ref 4===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def goodRet(self, result, cipher):
+ logger.debug(f"Result for base is true, where result is {result}")
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": True,
+ "Plaintext": result,
+ "Cipher": cipher,
+ "Extra Information": None,
+ }
+
===========changed ref 5===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def decrypt(self, text):
+ logger.debug("Attempting base decoding")
+
+ bases = [
+ self.base32(text),
+ self.base16(text),
+ self.base64(text),
+ ]
+ for answer in bases:
+ try:
+ if answer["IsPlaintext?"]:
+ # good answer
+ logger.debug(f"Returning true for {answer}")
+ return answer
+ except TypeError:
+ continue
+ # Base85
+ # if nothing works, it has failed.
+ return self.badRet()
+
===========changed ref 6===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def base16(self, text):
+ """Base16 decode
+
+ args:
+ text -> text to decode
+ returns:
+ the text decoded as base16
+ """
+ logger.debug("attempting base32")
+ result = None
+ try:
+ result = base64.b16decode(text)
+ # yeet turning b strings into normal stringy bois
+ result = result.decode("utf-8")
+ except UnicodeDecodeError as e:
+ None
+ except binascii.Error as e:
+ None
+ except ValueError:
+ None
+ if self.lc.checkLanguage(result) and result != "None":
+ logger.debug(f"Base16 successful, {result}")
+ return self.goodRet(result, cipher="Base16")
+
===========changed ref 7===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def base85(self, text):
+ """Base85 decode
+
+ args:
+ text -> text to decode
+ returns:
+ the text decoded as base85
+ """
+ logger.debug("Attempting base85")
+ result = None
+ try:
+ result = base64.b85decode(text)
+ # yeet turning b strings into normal stringy bois
+ result = result.decode("utf-8")
+ except UnicodeDecodeError as e:
+ None
+ except binascii.Error as e:
+ None
+ except ValueError:
+ None
+
+ if self.lc.checkLanguage(result) and result != "None":
+ logger.debug(f"Base85 successful, {result}")
+ return self.goodRet(result, cipher="Base85")
+
===========changed ref 8===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def base32(self, text):
+ """Base32 decode
+
+ args:
+ text -> text to decode
+ returns:
+ the text decoded as base32
+ """
+ logger.debug("attempting base32")
+ result = None
+ try:
+ result = base64.b32decode(text)
+ # yeet turning b strings into normal stringy bois
+ result = result.decode("utf-8")
+ except UnicodeDecodeError as e:
+ None
+ except binascii.Error as e:
+ None
+ except ValueError:
+ None
+
+ if self.lc.checkLanguage(result) and result != "None":
+ logger.debug(f"base32 successful, {result}")
+ return self.goodRet(result, cipher="Base32")
+
===========changed ref 9===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def base64(self, text):
+ """Bases decode
+
+ args:
+ text -> text to decode
+ returns:
+ the text decoded as base64
+ """
+ logger.debug(f"Attempting base64")
+ result = None
+ try:
+ result = base64.b64decode(text)
+ # yeet turning b strings into normal stringy bois
+ result = result.decode("utf-8")
+ except UnicodeDecodeError as e:
+ None
+ except binascii.Error as e:
+ None
+ except ValueError:
+ None
+
+ if self.lc.checkLanguage(result) and result != "None":
+ logger.debug(f"Bases successful, returning {result}")
+ return self.goodRet(result, cipher="Bases")
+
|
ciphey.__main__/Ciphey.decrypt
|
Modified
|
Ciphey~Ciphey
|
c4b4a667e2228c5bfd0a9dfe4da2c730a68c0fcc
|
Fixing bases & print statements in main
|
<0>:<del> print("The decrypt method is called")
<14>:<del>
<15>:<del> print(result)
|
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
<0> print("The decrypt method is called")
<1> """Performs the decryption of text
<2>
<3> Creates the probability table, calls one_level_of_decryption
<4>
<5> Args:
<6> None, it uses class variables.
<7>
<8> Returns:
<9> None
<10> """
<11> # Read the documentation for more on this function.
<12> # checks to see if inputted text is plaintext
<13> result = self.lc.checkLanguage(self.text)
<14>
<15> print(result)
<16> if result:
<17> print("You inputted plain text!")
<18> print(f"Returning {self.text}")
<19> return self.text
<20> self.probability_distribution: dict = self.ai.predictnn(self.text)[0]
<21> self.what_to_choose: dict = {
<22> self.hash: {
<23> "sha1": self.probability_distribution[0],
<24> "md5": self.probability_distribution[1],
<25> "sha256": self.probability_distribution[2],
<26> "sha512": self.probability_distribution[3],
<27> },
<28> self.basic: {"caesar": self.probability_distribution[4]},
<29> "plaintext": {"plaintext": self.probability_distribution[5]},
<30> self.encoding: {
<31> "reverse": self.probability_distribution[6],
<32> "base64": self.probability_distribution[7],
<33> "binary": self.probability_distribution[8],
<34> "hexadecimal": self.probability_distribution[9],
<35> "ascii": self.probability_distribution[10],
<36> "morse": self.probability_distribution[11],
<37> },
<38> }
<39>
<40> logger.debug(
<41> f"The probability table before 0.1 in __main__ is {</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.what_to_choose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.what_to_choose}"
)
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
# Creates and prints the probability table
if not self.greppable:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceprobtable(self.what_to_choose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.what_to_choose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
output = None
if self.level <= 1:
output = self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
output = self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
logger.debug(f"decrypt is outputting {output}")
return output
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey
one_level_of_decryption() -> None
one_level_of_decryption(self) -> None
at: ciphey.__main__.Ciphey.__init__
self.ai = NeuralNetwork()
self.lc = lc.LanguageChecker()
self.mh = mh.mathsHelper()
self.text: str = text
self.basic = BasicParent(self.lc)
self.hash = HashParent()
self.encoding = EncodingParent(self.lc)
self.level: int = 1
self.sickomode: bool = False
self.greppable: bool = grep
self.probability_distribution: dict = {}
self.what_to_choose: dict = {}
at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker
checkLanguage(text: str) -> bool
at: ciphey.neuralNetworkMod.nn.NeuralNetwork
predictnn(text)
at: mathsHelper.mathsHelper
sort_prob_table(prob_table: dict) -> dict
===========changed ref 0===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
===========changed ref 1===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def __init__(self, lc):
+ self.lc = lc
+
===========changed ref 2===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+ """
+ turns base64 strings into normal strings
+ """
+
===========changed ref 3===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def badRet(self):
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": False,
+ "Plaintext": None,
+ "Cipher": None,
+ "Extra Information": None,
+ }
+
===========changed ref 4===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def goodRet(self, result, cipher):
+ logger.debug(f"Result for base is true, where result is {result}")
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": True,
+ "Plaintext": result,
+ "Cipher": cipher,
+ "Extra Information": None,
+ }
+
===========changed ref 5===========
# module: ciphey.Decryptor.Encoding.encodingParent
class EncodingParent:
def __init__(self, lc):
self.lc = lc
+ self.base64 = Bases(self.lc)
- self.base64 = Base64(self.lc)
self.binary = Binary(self.lc)
self.hex = Hexadecimal(self.lc)
self.ascii = Ascii(self.lc)
self.morse = MorseCode(self.lc)
===========changed ref 6===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def decrypt(self, text):
+ logger.debug("Attempting base decoding")
+
+ bases = [
+ self.base32(text),
+ self.base16(text),
+ self.base64(text),
+ ]
+ for answer in bases:
+ try:
+ if answer["IsPlaintext?"]:
+ # good answer
+ logger.debug(f"Returning true for {answer}")
+ return answer
+ except TypeError:
+ continue
+ # Base85
+ # if nothing works, it has failed.
+ return self.badRet()
+
===========changed ref 7===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def base16(self, text):
+ """Base16 decode
+
+ args:
+ text -> text to decode
+ returns:
+ the text decoded as base16
+ """
+ logger.debug("attempting base32")
+ result = None
+ try:
+ result = base64.b16decode(text)
+ # yeet turning b strings into normal stringy bois
+ result = result.decode("utf-8")
+ except UnicodeDecodeError as e:
+ None
+ except binascii.Error as e:
+ None
+ except ValueError:
+ None
+ if self.lc.checkLanguage(result) and result != "None":
+ logger.debug(f"Base16 successful, {result}")
+ return self.goodRet(result, cipher="Base16")
+
===========changed ref 8===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def base85(self, text):
+ """Base85 decode
+
+ args:
+ text -> text to decode
+ returns:
+ the text decoded as base85
+ """
+ logger.debug("Attempting base85")
+ result = None
+ try:
+ result = base64.b85decode(text)
+ # yeet turning b strings into normal stringy bois
+ result = result.decode("utf-8")
+ except UnicodeDecodeError as e:
+ None
+ except binascii.Error as e:
+ None
+ except ValueError:
+ None
+
+ if self.lc.checkLanguage(result) and result != "None":
+ logger.debug(f"Base85 successful, {result}")
+ return self.goodRet(result, cipher="Base85")
+
|
ciphey.__main__/Ciphey.produceprobtable
|
Modified
|
Ciphey~Ciphey
|
c4b4a667e2228c5bfd0a9dfe4da2c730a68c0fcc
|
Fixing bases & print statements in main
|
<28>:<add> # converts "Bases" to "Base"
<del> # converts "Base64" to "Base"
|
# module: ciphey.__main__
class Ciphey:
def produceprobtable(self, prob_table) -> None:
<0> """Produces the probability table using Rich's API
<1>
<2> Uses Rich's API to print the probability table.
<3>
<4> Args:
<5> prob_table -> the probability table generated by the neural network
<6>
<7> Returns:
<8> None, but prints the probability table.
<9>
<10> """
<11> logger.debug(f"Producing log table")
<12> table = Table(show_header=True, header_style="bold magenta")
<13> table.add_column("Name of Cipher")
<14> table.add_column("Probability", justify="right")
<15> # for every key, value in dict add a row
<16> # I think key is self.caesarcipher and not "caesar cipher"
<17> # i must callName() somewhere else in this code
<18> sorted_dic: dict = {}
<19> for k, v in prob_table.items():
<20> for key, value in v.items():
<21> # Prevents the table from showing pointless 0.01 probs as they're faked
<22> if value == 0.01:
<23> continue
<24> # gets the string ready to print
<25> logger.debug(f"Key is {str(key)} and value is {str(value)}")
<26> val: int = round(self.mh.percentage(value, 1), 2)
<27> key_str: str = str(key).capitalize()
<28> # converts "Base64" to "Base"
<29> if "Base" in key_str:
<30> key_str = key_str[0:-2]
<31> sorted_dic[key_str] = val
<32> logger.debug(f"The value as percentage is {val} and key is {key_str}")
<33> sorted_dic: dict = {
<34> k: v
<35> for k, v in sorted</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def produceprobtable(self, prob_table) -> None:
# offset: 1
sorted_dic.items(), key=lambda item: item[1], reverse=True
)
}
for k, v in sorted_dic.items():
table.add_row(k, str(v) + "%")
self.console.print(table)
return None
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.mh = mh.mathsHelper()
self.console = Console()
at: ciphey.mathsHelper.mathsHelper
percentage(part: float, whole: float) -> float
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
- print("The decrypt method is called")
"""Performs the decryption of text
Creates the probability table, calls one_level_of_decryption
Args:
None, it uses class variables.
Returns:
None
"""
# Read the documentation for more on this function.
# checks to see if inputted text is plaintext
result = self.lc.checkLanguage(self.text)
-
- print(result)
if result:
print("You inputted plain text!")
print(f"Returning {self.text}")
return self.text
self.probability_distribution: dict = self.ai.predictnn(self.text)[0]
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.what_to_choose}"
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.what_to_choose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.what_to_choose}"
)
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
# Creates and prints the probability table
if not self.greppable:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceprobtable(self.what_to_choose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.what_to_choose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
output = None
if self.level <= 1:
output = self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
output = self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========changed ref 2===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
===========changed ref 3===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def __init__(self, lc):
+ self.lc = lc
+
===========changed ref 4===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+ """
+ turns base64 strings into normal strings
+ """
+
===========changed ref 5===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def badRet(self):
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": False,
+ "Plaintext": None,
+ "Cipher": None,
+ "Extra Information": None,
+ }
+
===========changed ref 6===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def goodRet(self, result, cipher):
+ logger.debug(f"Result for base is true, where result is {result}")
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": True,
+ "Plaintext": result,
+ "Cipher": cipher,
+ "Extra Information": None,
+ }
+
===========changed ref 7===========
# module: ciphey.Decryptor.Encoding.encodingParent
class EncodingParent:
def __init__(self, lc):
self.lc = lc
+ self.base64 = Bases(self.lc)
- self.base64 = Base64(self.lc)
self.binary = Binary(self.lc)
self.hex = Hexadecimal(self.lc)
self.ascii = Ascii(self.lc)
self.morse = MorseCode(self.lc)
===========changed ref 8===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def decrypt(self, text):
+ logger.debug("Attempting base decoding")
+
+ bases = [
+ self.base32(text),
+ self.base16(text),
+ self.base64(text),
+ ]
+ for answer in bases:
+ try:
+ if answer["IsPlaintext?"]:
+ # good answer
+ logger.debug(f"Returning true for {answer}")
+ return answer
+ except TypeError:
+ continue
+ # Base85
+ # if nothing works, it has failed.
+ return self.badRet()
+
|
ciphey.__main__/Ciphey.one_level_of_decryption
|
Modified
|
Ciphey~Ciphey
|
c4b4a667e2228c5bfd0a9dfe4da2c730a68c0fcc
|
Fixing bases & print statements in main
|
<17>:<del> print(f"One level returning {output}")
|
# module: ciphey.__main__
class Ciphey:
def one_level_of_decryption(self) -> None:
<0> """Performs one level of encryption.
<1>
<2> Either uses alive_bar or not depending on if self.greppable is set.
<3>
<4> Returns:
<5> None.
<6>
<7> """
<8> # Calls one level of decryption
<9> # mainly used to control the progress bar
<10> output = None
<11> if self.greppable:
<12> logger.debug("__main__ is running as greppable")
<13> output = self.decrypt_normal()
<14> else:
<15> logger.debug("__main__ is running with progress bar")
<16> output = self.decrypt_normal()
<17> print(f"One level returning {output}")
<18> return output
<19>
|
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.greppable: bool = grep
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def produceprobtable(self, prob_table) -> None:
"""Produces the probability table using Rich's API
Uses Rich's API to print the probability table.
Args:
prob_table -> the probability table generated by the neural network
Returns:
None, but prints the probability table.
"""
logger.debug(f"Producing log table")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name of Cipher")
table.add_column("Probability", justify="right")
# for every key, value in dict add a row
# I think key is self.caesarcipher and not "caesar cipher"
# i must callName() somewhere else in this code
sorted_dic: dict = {}
for k, v in prob_table.items():
for key, value in v.items():
# Prevents the table from showing pointless 0.01 probs as they're faked
if value == 0.01:
continue
# gets the string ready to print
logger.debug(f"Key is {str(key)} and value is {str(value)}")
val: int = round(self.mh.percentage(value, 1), 2)
key_str: str = str(key).capitalize()
+ # converts "Bases" to "Base"
- # converts "Base64" to "Base"
if "Base" in key_str:
key_str = key_str[0:-2]
sorted_dic[key_str] = val
logger.debug(f"The value as percentage is {val} and key is {key_str}")
sorted_dic: dict = {
k: v
for k, v in sorted(
sorted_dic.items(), key=lambda item: item[1], reverse=</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def produceprobtable(self, prob_table) -> None:
# offset: 1
<s>
for k, v in sorted(
sorted_dic.items(), key=lambda item: item[1], reverse=True
)
}
for k, v in sorted_dic.items():
table.add_row(k, str(v) + "%")
self.console.print(table)
return None
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
- print("The decrypt method is called")
"""Performs the decryption of text
Creates the probability table, calls one_level_of_decryption
Args:
None, it uses class variables.
Returns:
None
"""
# Read the documentation for more on this function.
# checks to see if inputted text is plaintext
result = self.lc.checkLanguage(self.text)
-
- print(result)
if result:
print("You inputted plain text!")
print(f"Returning {self.text}")
return self.text
self.probability_distribution: dict = self.ai.predictnn(self.text)[0]
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.what_to_choose}"
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose</s>
===========changed ref 3===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.what_to_choose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.what_to_choose}"
)
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
# Creates and prints the probability table
if not self.greppable:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceprobtable(self.what_to_choose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.what_to_choose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
output = None
if self.level <= 1:
output = self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
output = self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========changed ref 4===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
===========changed ref 5===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def __init__(self, lc):
+ self.lc = lc
+
===========changed ref 6===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+ """
+ turns base64 strings into normal strings
+ """
+
===========changed ref 7===========
+ # module: ciphey.Decryptor.Encoding.bases
+
+
+ class Bases:
+
+ def badRet(self):
+ return {
+ "lc": self.lc,
+ "IsPlaintext?": False,
+ "Plaintext": None,
+ "Cipher": None,
+ "Extra Information": None,
+ }
+
|
ciphey.__main__/Ciphey.decrypt_normal
|
Modified
|
Ciphey~Ciphey
|
c4b4a667e2228c5bfd0a9dfe4da2c730a68c0fcc
|
Fixing bases & print statements in main
|
<11>:<add> logger.debug(f"In decrypt_normal")
<22>:<del> print(ret["Plaintext"])
<32>:<del> print(f"Decryption returning {ret}")
|
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
<0> """Called by one_level_of_decryption
<1>
<2> Performs a decryption, but mainly parses the internal data packet and prints useful information.
<3>
<4> Args:
<5> bar -> whether or not to use alive_Bar
<6>
<7> Returns:
<8> None, but prints.
<9>
<10> """
<11> for key, val in self.what_to_choose.items():
<12> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
<13> if not isinstance(key, str):
<14> key.setProbTable(val)
<15> ret: dict = key.decrypt(self.text)
<16> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<17> logger.debug(
<18> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<19> )
<20>
<21> if ret["IsPlaintext?"]:
<22> print(ret["Plaintext"])
<23> if self.cipher:
<24> if ret["Extra Information"] is not None:
<25> print(
<26> "The cipher used is",
<27> ret["Cipher"] + ".",
<28> ret["Extra Information"] + ".",
<29> )
<30> else:
<31> print("The cipher used is " + ret["Cipher"] + ".")
<32> print(f"Decryption returning {ret}")
<33> return ret
<34>
<35> logger.debug("No encryption found")
<36> print(
<37> """No encryption found. Here are some tips to help crack the cipher:
<38> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
<39> * If the probability table says 'Caesar Cipher</s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
# offset: 1
Ciphey cannot decrypt yet.
* If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \
and then HashCat to crack the hash.
* The encryption may not contain normal English plaintext. It could be coordinates or \
another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \
file of all attempted decryptions and manually search it."""
)
return None
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.text: str = text
self.cipher = cipher
self.what_to_choose: dict = {}
at: ciphey.__main__.Ciphey.decrypt
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def one_level_of_decryption(self) -> None:
"""Performs one level of encryption.
Either uses alive_bar or not depending on if self.greppable is set.
Returns:
None.
"""
# Calls one level of decryption
# mainly used to control the progress bar
output = None
if self.greppable:
logger.debug("__main__ is running as greppable")
output = self.decrypt_normal()
else:
logger.debug("__main__ is running with progress bar")
output = self.decrypt_normal()
- print(f"One level returning {output}")
return output
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def produceprobtable(self, prob_table) -> None:
"""Produces the probability table using Rich's API
Uses Rich's API to print the probability table.
Args:
prob_table -> the probability table generated by the neural network
Returns:
None, but prints the probability table.
"""
logger.debug(f"Producing log table")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name of Cipher")
table.add_column("Probability", justify="right")
# for every key, value in dict add a row
# I think key is self.caesarcipher and not "caesar cipher"
# i must callName() somewhere else in this code
sorted_dic: dict = {}
for k, v in prob_table.items():
for key, value in v.items():
# Prevents the table from showing pointless 0.01 probs as they're faked
if value == 0.01:
continue
# gets the string ready to print
logger.debug(f"Key is {str(key)} and value is {str(value)}")
val: int = round(self.mh.percentage(value, 1), 2)
key_str: str = str(key).capitalize()
+ # converts "Bases" to "Base"
- # converts "Base64" to "Base"
if "Base" in key_str:
key_str = key_str[0:-2]
sorted_dic[key_str] = val
logger.debug(f"The value as percentage is {val} and key is {key_str}")
sorted_dic: dict = {
k: v
for k, v in sorted(
sorted_dic.items(), key=lambda item: item[1], reverse=</s>
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def produceprobtable(self, prob_table) -> None:
# offset: 1
<s>
for k, v in sorted(
sorted_dic.items(), key=lambda item: item[1], reverse=True
)
}
for k, v in sorted_dic.items():
table.add_row(k, str(v) + "%")
self.console.print(table)
return None
===========changed ref 3===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
- print("The decrypt method is called")
"""Performs the decryption of text
Creates the probability table, calls one_level_of_decryption
Args:
None, it uses class variables.
Returns:
None
"""
# Read the documentation for more on this function.
# checks to see if inputted text is plaintext
result = self.lc.checkLanguage(self.text)
-
- print(result)
if result:
print("You inputted plain text!")
print(f"Returning {self.text}")
return self.text
self.probability_distribution: dict = self.ai.predictnn(self.text)[0]
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.what_to_choose}"
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose</s>
|
ciphey.__main__/call_encryption
|
Modified
|
Ciphey~Ciphey
|
c4b4a667e2228c5bfd0a9dfe4da2c730a68c0fcc
|
Fixing bases & print statements in main
|
<0>:<del> print("calling encryption")
<8>:<del> print("calling ciphey")
<11>:<del> print(f"Ciphey returns {output}")
|
# module: ciphey.__main__
def call_encryption(
greppable=False, Cipher=False, text=None, debug=False, cipher=False
):
<0> print("calling encryption")
<1> """Function to call Encryption, only used because of arguments.
<2> Basically, this is what Main used to be before I had to deal with arg parsing
<3> Returns:
<4> The output of the decryption.
<5> """
<6> output = None
<7> if text is not None:
<8> print("calling ciphey")
<9> cipher_obj = Ciphey(text, greppable, Cipher, debug)
<10> output = cipher_obj.decrypt()
<11> print(f"Ciphey returns {output}")
<12> return output
<13>
|
===========unchanged ref 0===========
at: ciphey.__main__
Ciphey(text, grep=False, cipher=False, debug=False)
main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict
at: ciphey.__main__.Ciphey
decrypt(self)
decrypt()
===========changed ref 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
- print("The decrypt method is called")
"""Performs the decryption of text
Creates the probability table, calls one_level_of_decryption
Args:
None, it uses class variables.
Returns:
None
"""
# Read the documentation for more on this function.
# checks to see if inputted text is plaintext
result = self.lc.checkLanguage(self.text)
-
- print(result)
if result:
print("You inputted plain text!")
print(f"Returning {self.text}")
return self.text
self.probability_distribution: dict = self.ai.predictnn(self.text)[0]
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
logger.debug(
f"The probability table before 0.1 in __main__ is {self.what_to_choose}"
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose</s>
===========changed ref 1===========
# module: ciphey.__main__
class Ciphey:
def decrypt(self):
# offset: 1
<s>
)
# sorts each individual sub-dictionary
for key, value in self.what_to_choose.items():
for k, v in value.items():
# Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions.
if v < 0.01:
self.what_to_choose[key][k] = 0.01
logger.debug(
f"The probability table after 0.1 in __main__ is {self.what_to_choose}"
)
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
# Creates and prints the probability table
if not self.greppable:
logger.debug(f"Self.greppable is {self.greppable}")
self.produceprobtable(self.what_to_choose)
logger.debug(
f"The new probability table after sorting in __main__ is {self.what_to_choose}"
)
"""
#for each dictionary in the dictionary
# sort that dictionary
#sort the overall dictionary by the first value of the new dictionary
"""
output = None
if self.level <= 1:
output = self.one_level_of_decryption()
else:
if self.sickomode:
print("Sicko mode entered")
f = open("decryptionContents.txt", "w")
output = self.one_level_of_decryption(file=f)
for i in range(0, self.level):
# open file and go through each text item
pass
===========changed ref 2===========
# module: ciphey.__main__
class Ciphey:
def one_level_of_decryption(self) -> None:
"""Performs one level of encryption.
Either uses alive_bar or not depending on if self.greppable is set.
Returns:
None.
"""
# Calls one level of decryption
# mainly used to control the progress bar
output = None
if self.greppable:
logger.debug("__main__ is running as greppable")
output = self.decrypt_normal()
else:
logger.debug("__main__ is running with progress bar")
output = self.decrypt_normal()
- print(f"One level returning {output}")
return output
===========changed ref 3===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
"""Called by one_level_of_decryption
Performs a decryption, but mainly parses the internal data packet and prints useful information.
Args:
bar -> whether or not to use alive_Bar
Returns:
None, but prints.
"""
+ logger.debug(f"In decrypt_normal")
for key, val in self.what_to_choose.items():
# https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
if not isinstance(key, str):
key.setProbTable(val)
ret: dict = key.decrypt(self.text)
logger.debug(f"Decrypt normal in __main__ ret is {ret}")
logger.debug(
f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
)
if ret["IsPlaintext?"]:
- print(ret["Plaintext"])
if self.cipher:
if ret["Extra Information"] is not None:
print(
"The cipher used is",
ret["Cipher"] + ".",
ret["Extra Information"] + ".",
)
else:
print("The cipher used is " + ret["Cipher"] + ".")
- print(f"Decryption returning {ret}")
return ret
logger.debug("No encryption found")
print(
"""No encryption found. Here are some tips to help crack the cipher:
* Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
* If the probability table says 'Caesar Cipher' then it is a normal encryption that \
Ciphey cannot decrypt yet.
*</s>
===========changed ref 4===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
# offset: 1
<s> table says 'Caesar Cipher' then it is a normal encryption that \
Ciphey cannot decrypt yet.
* If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \
and then HashCat to crack the hash.
* The encryption may not contain normal English plaintext. It could be coordinates or \
another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \
file of all attempted decryptions and manually search it."""
)
return None
|
ciphey.__main__/Ciphey.decrypt_normal
|
Modified
|
Ciphey~Ciphey
|
79c32446807668796519d871791c3954a49a6e47
|
Fixed serious main bug
|
<23>:<add> logger.debug(f"Ret is plaintext")
<add> print(ret['Plaintext'])
|
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
<0> """Called by one_level_of_decryption
<1>
<2> Performs a decryption, but mainly parses the internal data packet and prints useful information.
<3>
<4> Args:
<5> bar -> whether or not to use alive_Bar
<6>
<7> Returns:
<8> None, but prints.
<9>
<10> """
<11> logger.debug(f"In decrypt_normal")
<12> for key, val in self.what_to_choose.items():
<13> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string
<14> if not isinstance(key, str):
<15> key.setProbTable(val)
<16> ret: dict = key.decrypt(self.text)
<17> logger.debug(f"Decrypt normal in __main__ ret is {ret}")
<18> logger.debug(
<19> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}"
<20> )
<21>
<22> if ret["IsPlaintext?"]:
<23> if self.cipher:
<24> if ret["Extra Information"] is not None:
<25> print(
<26> "The cipher used is",
<27> ret["Cipher"] + ".",
<28> ret["Extra Information"] + ".",
<29> )
<30> else:
<31> print("The cipher used is " + ret["Cipher"] + ".")
<32> return ret
<33>
<34> logger.debug("No encryption found")
<35> print(
<36> """No encryption found. Here are some tips to help crack the cipher:
<37> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc.
<38> * If the probability table says 'Caesar Cipher' then it is a normal encryption that \
<39> </s>
|
===========below chunk 0===========
# module: ciphey.__main__
class Ciphey:
def decrypt_normal(self, bar=None) -> None:
# offset: 1
* If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \
and then HashCat to crack the hash.
* The encryption may not contain normal English plaintext. It could be coordinates or \
another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \
file of all attempted decryptions and manually search it."""
)
return None
===========unchanged ref 0===========
at: ciphey.__main__.Ciphey.__init__
self.text: str = text
self.cipher = cipher
self.what_to_choose: dict = {}
at: ciphey.__main__.Ciphey.decrypt
self.what_to_choose: dict = {
self.hash: {
"sha1": self.probability_distribution[0],
"md5": self.probability_distribution[1],
"sha256": self.probability_distribution[2],
"sha512": self.probability_distribution[3],
},
self.basic: {"caesar": self.probability_distribution[4]},
"plaintext": {"plaintext": self.probability_distribution[5]},
self.encoding: {
"reverse": self.probability_distribution[6],
"base64": self.probability_distribution[7],
"binary": self.probability_distribution[8],
"hexadecimal": self.probability_distribution[9],
"ascii": self.probability_distribution[10],
"morse": self.probability_distribution[11],
},
}
self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.