mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 15:01:08 +00:00
added gronsfeld cipher implementation (#11835)
* added gronsfeld cipher implementation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * from string import ascii_uppercase * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update gronsfeld_cipher.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
cfd6d095f1
commit
dba8eecb47
45
ciphers/gronsfeld_cipher.py
Normal file
45
ciphers/gronsfeld_cipher.py
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
from string import ascii_uppercase
|
||||||
|
|
||||||
|
|
||||||
|
def gronsfeld(text: str, key: str) -> str:
|
||||||
|
"""
|
||||||
|
Encrypt plaintext with the Gronsfeld cipher
|
||||||
|
|
||||||
|
>>> gronsfeld('hello', '412')
|
||||||
|
'LFNPP'
|
||||||
|
>>> gronsfeld('hello', '123')
|
||||||
|
'IGOMQ'
|
||||||
|
>>> gronsfeld('', '123')
|
||||||
|
''
|
||||||
|
>>> gronsfeld('yes, ¥€$ - _!@#%?', '0')
|
||||||
|
'YES, ¥€$ - _!@#%?'
|
||||||
|
>>> gronsfeld('yes, ¥€$ - _!@#%?', '01')
|
||||||
|
'YFS, ¥€$ - _!@#%?'
|
||||||
|
>>> gronsfeld('yes, ¥€$ - _!@#%?', '012')
|
||||||
|
'YFU, ¥€$ - _!@#%?'
|
||||||
|
>>> gronsfeld('yes, ¥€$ - _!@#%?', '')
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ZeroDivisionError: integer modulo by zero
|
||||||
|
"""
|
||||||
|
ascii_len = len(ascii_uppercase)
|
||||||
|
key_len = len(key)
|
||||||
|
encrypted_text = ""
|
||||||
|
keys = [int(char) for char in key]
|
||||||
|
upper_case_text = text.upper()
|
||||||
|
|
||||||
|
for i, char in enumerate(upper_case_text):
|
||||||
|
if char in ascii_uppercase:
|
||||||
|
new_position = (ascii_uppercase.index(char) + keys[i % key_len]) % ascii_len
|
||||||
|
shifted_letter = ascii_uppercase[new_position]
|
||||||
|
encrypted_text += shifted_letter
|
||||||
|
else:
|
||||||
|
encrypted_text += char
|
||||||
|
|
||||||
|
return encrypted_text
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
from doctest import testmod
|
||||||
|
|
||||||
|
testmod()
|
Loading…
Reference in New Issue
Block a user