- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathrsa_cipher.py
149 lines (116 loc) · 4.76 KB
/
rsa_cipher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
importos
importsys
from . importrsa_key_generatorasrkg
DEFAULT_BLOCK_SIZE=128
BYTE_SIZE=256
defget_blocks_from_text(
message: str, block_size: int=DEFAULT_BLOCK_SIZE
) ->list[int]:
message_bytes=message.encode("ascii")
block_ints= []
forblock_startinrange(0, len(message_bytes), block_size):
block_int=0
foriinrange(block_start, min(block_start+block_size, len(message_bytes))):
block_int+=message_bytes[i] * (BYTE_SIZE** (i%block_size))
block_ints.append(block_int)
returnblock_ints
defget_text_from_blocks(
block_ints: list[int], message_length: int, block_size: int=DEFAULT_BLOCK_SIZE
) ->str:
message: list[str] = []
forblock_intinblock_ints:
block_message: list[str] = []
foriinrange(block_size-1, -1, -1):
iflen(message) +i<message_length:
ascii_number=block_int// (BYTE_SIZE**i)
block_int=block_int% (BYTE_SIZE**i)
block_message.insert(0, chr(ascii_number))
message.extend(block_message)
return"".join(message)
defencrypt_message(
message: str, key: tuple[int, int], block_size: int=DEFAULT_BLOCK_SIZE
) ->list[int]:
encrypted_blocks= []
n, e=key
forblockinget_blocks_from_text(message, block_size):
encrypted_blocks.append(pow(block, e, n))
returnencrypted_blocks
defdecrypt_message(
encrypted_blocks: list[int],
message_length: int,
key: tuple[int, int],
block_size: int=DEFAULT_BLOCK_SIZE,
) ->str:
decrypted_blocks= []
n, d=key
forblockinencrypted_blocks:
decrypted_blocks.append(pow(block, d, n))
returnget_text_from_blocks(decrypted_blocks, message_length, block_size)
defread_key_file(key_filename: str) ->tuple[int, int, int]:
withopen(key_filename) asfo:
content=fo.read()
key_size, n, eor_d=content.split(",")
return (int(key_size), int(n), int(eor_d))
defencrypt_and_write_to_file(
message_filename: str,
key_filename: str,
message: str,
block_size: int=DEFAULT_BLOCK_SIZE,
) ->str:
key_size, n, e=read_key_file(key_filename)
ifkey_size<block_size*8:
sys.exit(
f"ERROR: Block size is {block_size*8} bits and key size is {key_size} "
"bits. The RSA cipher requires the block size to be equal to or greater "
"than the key size. Either decrease the block size or use different keys."
)
encrypted_blocks= [str(i) foriinencrypt_message(message, (n, e), block_size)]
encrypted_content=",".join(encrypted_blocks)
encrypted_content=f"{len(message)}_{block_size}_{encrypted_content}"
withopen(message_filename, "w") asfo:
fo.write(encrypted_content)
returnencrypted_content
defread_from_file_and_decrypt(message_filename: str, key_filename: str) ->str:
key_size, n, d=read_key_file(key_filename)
withopen(message_filename) asfo:
content=fo.read()
message_length_str, block_size_str, encrypted_message=content.split("_")
message_length=int(message_length_str)
block_size=int(block_size_str)
ifkey_size<block_size*8:
sys.exit(
f"ERROR: Block size is {block_size*8} bits and key size is {key_size} "
"bits. The RSA cipher requires the block size to be equal to or greater "
"than the key size. Were the correct key file and encrypted file specified?"
)
encrypted_blocks= []
forblockinencrypted_message.split(","):
encrypted_blocks.append(int(block))
returndecrypt_message(encrypted_blocks, message_length, (n, d), block_size)
defmain() ->None:
filename="encrypted_file.txt"
response=input(r"Encrypt\Decrypt [e\d]: ")
ifresponse.lower().startswith("e"):
mode="encrypt"
elifresponse.lower().startswith("d"):
mode="decrypt"
ifmode=="encrypt":
ifnotos.path.exists("rsa_pubkey.txt"):
rkg.make_key_files("rsa", 1024)
message=input("\nEnter message: ")
pubkey_filename="rsa_pubkey.txt"
print(f"Encrypting and writing to {filename}...")
encrypted_text=encrypt_and_write_to_file(filename, pubkey_filename, message)
print("\nEncrypted text:")
print(encrypted_text)
elifmode=="decrypt":
privkey_filename="rsa_privkey.txt"
print(f"Reading from {filename} and decrypting...")
decrypted_text=read_from_file_and_decrypt(filename, privkey_filename)
print("writing decryption to rsa_decryption.txt...")
withopen("rsa_decryption.txt", "w") asdec:
dec.write(decrypted_text)
print("\nDecryption:")
print(decrypted_text)
if__name__=="__main__":
main()