I made a very simple encryption and decryption program to encrypt files by incrementing all bytes by 6. However, in testing, only text files work. If I use it to encrypt and decrypt photos, the result is not readable by the OS.
Code in Python:
JavaScript
x
61
61
1
import os.path
2
3
4
class fileEncryptor:
5
6
@staticmethod
7
def encrypt(fileLocation, destination):
8
if os.path.exists(fileLocation):
9
file = open(fileLocation, "rb")
10
fileContents = file.read() # fileContents is a byte string
11
file.close()
12
13
btAr = bytearray(fileContents) # Byte string needs to be changed to byte array to manipulate
14
15
16
length = len(btAr)
17
n = 0
18
while n < length:
19
increment = 6
20
if btAr[n] <= 249:
21
btAr[n] = btAr[n] + increment
22
if 249 < btAr[n] <= 255:
23
btAr[n] = btAr[n] - 250
24
n = n + 1
25
26
encryptedFile = open(destination, "wb")
27
encryptedFile.write(btAr)
28
encryptedFile.close()
29
else:
30
print("File does not exist")
31
32
@staticmethod
33
def decrypt(fileLocation, destination):
34
if os.path.exists(fileLocation):
35
file = open(fileLocation, "rb")
36
fileContents = file.read()
37
file.close()
38
39
btAr = bytearray(fileContents)
40
41
length = len(btAr)
42
n = 0
43
while n < length:
44
increment = 6
45
if 5 < btAr[n] <= 255:
46
btAr[n] = btAr[n] - increment
47
if btAr[n] <= 5:
48
btAr[n] = btAr[n] + 250
49
n = n + 1
50
51
decryptedFile = open(destination, "wb")
52
decryptedFile.write(btAr)
53
decryptedFile.close()
54
else:
55
print("File does not exist")
56
57
58
if __name__ == "__main__":
59
fileEncryptor.encrypt("D:Python ProjectsDesignerProjectic.ico", "D:Python ProjectsDesignerProjectoutputic.ico")
60
fileEncryptor.decrypt("D:Python ProjectsDesignerProjectoutputic.ico", "D:Python ProjectsDesignerProjectoutputi.ico")
61
Advertisement
Answer
This part needs to be changed to a else
:
JavaScript
1
5
1
if btAr[n] <= 249:
2
btAr[n] = btAr[n] + increment
3
if 249 < btAr[n] <= 255:
4
btAr[n] = btAr[n] - 250
5
Like this :
JavaScript
1
5
1
if btAr[n] <= 249:
2
btAr[n] = btAr[n] + increment
3
else:
4
btAr[n] = btAr[n] - 250
5
Otherwise, if the first if
is true, the byte is changed and the second if
might be runned, applying twice the increment.
Same for the decryption.