简体   繁体   中英

Python base64 encryptstring

I have tried to build a function that can translate an encrypted string which generated by this function:

def encrypt2(message,key):
return base64.encodestring("".join([chr(ord(message[i]) ^ ord(key[i % len(key)])) 
                                 for i in xrange(len(message))]))

So the function take a string and a key which have 4 digits (the key is a string), and encode him using the encodestring function. The function I build to decode it looks the same but with one difference, the encodestring changes to decodestring. To my opinion it should work, but it prints an error message, "incorrect padding". What should I change in the decryption function to solve this problem?

def decrypt2(message,key):
    return (base64.decodestring("".join([chr(ord(message[i]) ^ ord(key[i % len(key)])) 
                                      for i in xrange(len(message))])))

This what I tried to execute:

message = "n"
key = "8080"
encrypt = encrypt2(message,key)
decrypt = decrypt2(encrypt,key)
print "Message: %s \nEncrypt: %s \nDecrypt: %s" %(message,encrypt,decrypt)

and as I said, the line with the decryption returned an "incorrect padding" error.

Your (insecure) "encryption" function returns ordinary base64-encoded text, encoding your ciphertext.

Your decryption function decrypts the input text (which is actually base64), then passes the "decrypted" text to the base64 decoder.

Since the original base64 text is not encrypted, trying to decrypt it results in garbage, which is not valid base64.

To make the suggestions concrete, replace your decoding function like so:

def decrypt2(message,key):
    decoded = base64.decodestring(message)
    return "".join(chr(ord(decoded[i]) ^ ord(key[i % len(key)]))
                   for i in xrange(len(decoded)))

There are more efficient ways to do this ;-) For example,

def decrypt2(message, key):
    from itertools import cycle
    decoded = base64.decodestring(message)
    return "".join(chr(a ^ b) for a, b in zip(map(ord, decoded),
                                              cycle(map(ord, key))))

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