简体   繁体   中英

Special Chars not converting in to binary well in python

I am working an a XOR encryption model in Python and thus far everything works great except for numbers, and punctuation.

Any number or punctuation will give you a invalid binary string however, any basic letters at least in the english alphabet work.

What am I doing wrong here? I have traced it down to this method:

def IMpassEnc(self,password):
    binaryList = ""
    for i in password:
        if i == " ":
            binaryList += "00100000"  #adding binary for space
        else:
            tmp = bin(int(binascii.hexlify(i),16)) #Binary Conversion
            newtemp = tmp.replace('b','')  
            binaryList += newtemp
    return binaryList

You need to generate binary representations that are 8 bits wide; bin() does not give you that.

The better way to produce these results is to use format(value, '08b') ; this produces 8-character wide binary representations, padded with 0. Moreover; ord() would be a much more direct way to get the integer codepoint for a given character:

>>> format(ord(' '), '08b')
'00100000'
>>> format(ord('a'), '08b')
'01100001'
>>> format(ord('!'), '08b')
'00100001'

or, put together using ''.join() :

def IMpassEnc(self, password):
    return ''.join(format(ord(c), '08b') for c in password)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM