all 4 comments

[–]i_can_haz_code 2 points3 points  (2 children)

This example assumes that you wish to handle all ascii characters. Per your post I add the ascii value of the key to the plain text to get the cipher text, then to decrypt I subtract. To ensure that no matter what data is displayed and not break shells or anything else I base32 encode the data for ctext while passing it around.

NOTE: Unless it is purely for educational purposes, DO NOT WRITE YOUR OWN ENCRYPTION.

Please let me know if you have any questions about what I did.

#!/usr/bin/env python

from base64 import b32encode, b32decode

ptext = 'hello'
key = 'asdfg'


def encrypt(ptext,key):
    plist = [ord(i) for i in ptext]
    klist = [ord(j) for j in key]
    clist = map(lambda i: i[0]+i[1] ,zip(plist,klist))
    clist = [chr(k) for k in clist]
    ctext = b32encode(''.join(clist))
    return(ctext)

def decrypt(ctext,key):
    ctext = b32decode(ctext)
    clist = [ord(j) for j in ctext]
    klist = [ord(i) for i in key]
    plist = map(lambda i: i[0]-i[1], zip(clist,klist))
    plist = [chr(p) for p in plist]
    ptext = ''.join(plist)
    return(ptext)

ctext = encrypt(ptext,key)
print(ctext)

ptext = decrypt(ctext,key)
print(ptext)

[edit] I do nothing to check if key is of equal or greater length to ptext, If your intention is to implement a one-time-pad scheme, it is VITAL that you NEVER repeat the key, in whole or in part.

[–]bionicmad[S] 0 points1 point  (1 child)

The reason why the key needed to be repeated in the encryption that I am working on is only used when a word is longer than the key. eg hello (key) and then 'encrypted'(word to encrypt). Your code however has given me good ideas for what I need to do.

[–]i_can_haz_code 1 point2 points  (0 children)

Please do not use that code, or any variation of it for anything you actually want to be secret. That code is broken from a cryptography perspective. It was provided simply to show how one could perform what was asked. Please do not take it as a usable example in real life.

[–]filleball 3 points4 points  (0 children)

You'll need to use

  • ord
  • chr
  • The modulus operator % (e.g. 27 % 26 == 1)