i'm trying write basic algorithm encrypting file. takes ascii value of each character in string , moves or down amount depending on how long password is, can layer more passwords on top.
def encrypt(s): lenstr=s.__len__() #used later working how far int moved s=list(s) #converts string list x in s: s[x]=ord(s[x]) #the same index of list = value of string s[x]=chr(s[x])#is eventualy gets changed str s=ord(s) line throwing error, added int() around didnt help, same error
you're getting thetypeerrorexception because value ofxin thes[x]=ord(s[x]) statement 1 of elements of s list, it's individual character string argument passed toencrypt(). fix that, loop through possible indices of s list happens same length original string:
def encrypt(s): lenstr=len(s) s=list(s) # convert string list in range(lenstr): s[i]=ord(s[i]) s[i]=chr(s[i]) this allow code run without getting error. description of encryption algorithm you're going implement, 1 thing watch out producing illegal 8-bit character values out of range of 0-255. can avoid problem applying mod operator % intermediate results keep values in proper range. here's mean:
def encrypt(s): lenstr = len(s) s = list(s) # convert string list in range(lenstr): s[i] = chr((ord(s[i]) + lenstr) % 256) return ''.join(s) # convert list string likewise, you'll have same thing when decrypt string:
def decrypt(s): lenstr = len(s) s = list(s) # convert string list in range(lenstr): s[i] = chr((ord(s[i]) - lenstr) % 256) return ''.join(s) # convert list string enc = encrypt('gnomorian') print('encrypted:', enc) dec = decrypt(enc) print('decrypted:', dec) output:
encrypted: pwxvx{rjw decrypted: gnomorian also note not characters ord() values in range of 0-255 printable, may want restrict encryption transformation more if that's requirement (that encrypted version printable).
Comments
Post a Comment