Skip to content

Instantly share code, notes, and snippets.

@Yousif-FJ
Last active April 16, 2022 19:17
Show Gist options
  • Save Yousif-FJ/e35e1ab9e2c656e581d49c76b257d84c to your computer and use it in GitHub Desktop.
Save Yousif-FJ/e35e1ab9e2c656e581d49c76b257d84c to your computer and use it in GitHub Desktop.
Q/Write a program that can encrypt and decrypt using the affine cipher
import string
def AffineEncrypt(input :string, key1: int, key2: int):
input = input.replace(" ", "")
result = ""
for letter in input:
cipheredLetter = (GetLetterIndex(letter)*key1+key2)%26
result += GetLetterFromIndex(cipheredLetter)
return result
def AffineDecrypt(input, key1, key2):
result = ""
for letter in input:
uncipheredLetter = ((GetLetterIndex(letter)-key2)*pow(key1, -1, 26))%26
result += GetLetterFromIndex(uncipheredLetter)
return result
def GetLetterIndex(letter):
return string.ascii_uppercase.index(letter.upper())
def GetLetterFromIndex(index):
return string.ascii_uppercase[index]
input = "hello"
key = (7,2)
cipherText = AffineEncrypt(input, key[0], key[1])
uncipheredText = AffineDecrypt(cipherText, key[0], key[1])
print(cipherText) #print ZEBBW
print(uncipheredText) #print HELLO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment