1

I am new to cryptography so I try to make a simple Caesar cipher program with python but it keeps returning only one letter. Can anyone help please? Here's my code:

def main():

    text = raw_input('input plainteks:')
    key  = int(raw_input('input key:'))

    print("plain teks :"+text)
    print("key :" +str(key))
    print("hasil cipher:", encrypt(text,key))

def encrypt(text,key):

    hasil = ''

    for i in range(len(text)): #
        char = text[i]

    if (char.isupper()):
        hasil += chr((ord(char) + key-65)%26 + 65)
    else:
        hasil += chr((ord(char) + key-97)%26 + 97)
    return hasil

Here when I try to run it:

input plainteks:melody  
input key:3 
plain teks :melody
key :3
hasil cipher: b
j_4321
  • 15,431
  • 3
  • 34
  • 61
  • 3
    I think you just need to indent the `if..else` in `encrypt` one more tab so that it occurs for each iteration of `i`. – SuperShoot Jul 20 '18 at 07:45
  • 1
    Side note: strings are iterable. Instead of `for i in range(len(text)):` you could simply do `for char in text:` – shmee Jul 20 '18 at 07:50
  • 2
    You should not be learning Python 2 in 2018. Python 3 is the current version and version 2 is slated to be end-of-lifed in 2020. This is already an extension; the original deadline was 2018. – tripleee Jul 20 '18 at 07:53
  • 1
    1 - Python 2 is approaching end of life. 2 - Never roll your own crypto lib for the real world. – ggdx Jul 20 '18 at 07:54

1 Answers1

0

Your if is not in the loop. The following code works:

def main():

    text = raw_input('input plainteks:')
    key  = int(raw_input('input key:'))

    print("plain teks: "+text)
    print("key: " +str(key))
    print("hasil cipher: "+encrypt(text,key))

def encrypt(text,key):
    hasil = ''
    for i in range(len(text)): #
        char = text[i]
        if (char.isupper()):
            hasil += chr((ord(char) + key-65)%26 + 65)
        else:
            hasil += chr((ord(char) + key-97)%26 + 97)
    return hasil

main()

Also you can use the secretpy module

from secretpy import Caesar

text = 'melody'
key = 3
print(text)
cipher = Caesar()
enc = cipher.encrypt(text, key)
print(enc)
TigerTV.ru
  • 1,058
  • 2
  • 16
  • 34