simple encrypt/decrypt lib in python with private key

前端 未结 5 909
[愿得一人]
[愿得一人] 2021-01-31 04:07

Is there a simple way to encrypt/decrypt a string with a key?

Something like:

key = \'1234\'
string =  \'hello world\'
encrypted_string = encrypt(key, st         


        
5条回答
  •  没有蜡笔的小新
    2021-01-31 04:53

    To expand on dsamersoff's answer.. This is simple and insecure, but for certain tasks may be useful. here's some code:

    import crypt
    import getpass
    import os.path
    
    def auth_func():
        return (raw_input('Username:'), getpass.getpass('Password:'))
    
    def xor(a,b):
        assert len(b) >= len(a)
        return "".join([chr( ord(a[i]) ^ ord(b[i])) for i in range(len(a))])
    
    # create a new credentials file if needed
    if not os.path.exists('cred'):
        with open('cred', 'w') as f:
            user, pwd =  auth_func()
            f.write ("{}\n".format(user))               
            f.write ("{}\n".format(xor(pwd, crypt.crypt('secret', 'words'))))
            f.close()
    
    # read credentials and print user/password
    with open('cred', 'r') as f:
        user, pwd = f.read().split('\n')[:2]
        print user
        print xor(pwd, crypt.crypt('secret', 'words'))
    

提交回复
热议问题