【问题标题】:writing a variable to a text file and encrypting it?将变量写入文本文件并对其进行加密?
【发布时间】:2015-09-18 14:31:31
【问题描述】:

我知道如何将用户输入保存到文本文件中,但我该如何加密呢?这是我将用户输入保存到文本文件的内容。我试过f.encrypt("Passwords_log.txt"但没有结果

import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
f.write(password)
f.write('\n')
f.close()
print("Done!")

【问题讨论】:

  • 你在哪里看到file.encrypt? :) 您可以在 Python 文档中阅读有关 File objects 的更多信息。
  • 您是要加密密码保存到文件中,还是先保存密码到文件中再加密文件?

标签: python security encryption save python-3.4


【解决方案1】:

有一些 Python 包值得一试,它们处理密码学。

Cryptography

PyCrypto

cryptography 的一个简单示例如下:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)

【讨论】:

    【解决方案2】:

    查看password hashing

    那么我建议你使用https://pythonhosted.org/passlib/ 或 pycrypto;取决于您选择的算法。

    这只是为了存储加密的密码。然后加密数据看看https://pypi.python.org/pypi/pycrypto/2.6.1

    【讨论】:

      【解决方案3】:

      我猜你想得到某种密码的哈希值,但文件对象与此无关。您可以尝试使用base64 编码(如here)或任何其他此类算法。

      您的代码:

      import time
      import base64
      password1 = raw_input("Please type a password: ")
      print("Your password has passed the verification!")
      time.sleep(1)
      print("Saving and encrypting password...")
      time.sleep(2)
      f=open("Passwords_log.txt",'a')
      password = base64.b64encode(password)
      f.write(password)
      f.write('\n')
      f.close()
      print("Done!")
      

      【讨论】:

        【解决方案4】:

        您说,您尝试了base64,但没有成功。以下是如何让它发挥作用:

        import base64
        import time
        password1 = input("Please type a password: ")
        print("Your password has passed the verification!")
        time.sleep(1)
        print("Saving and encrypting password...")
        time.sleep(2)
        f=open("Passwords_log.txt",'a')
        cr = base64.encodestring(password1)
        f.write(cr)
        f.write('\n')
        f.close()
        print("Done!")
        

        这不是真正的加密,我不建议将它用于密码,但是由于您在评论中说您尝试使用base64但它不起作用,我想我应该向您展示如何使用@ 987654325@ 在您的代码中。

        【讨论】:

        • 就像@Joe R 所说,Python 可能不是加密的最佳选择。有关更多详细信息,请参阅 crypto.stackexchange 的此答案。 crypto.stackexchange.com/a/19969
        猜你喜欢
        • 2014-02-26
        • 2013-01-23
        • 2016-04-16
        • 2016-01-27
        • 2022-01-21
        • 2018-12-12
        • 1970-01-01
        • 2018-01-01
        • 1970-01-01
        相关资源
        最近更新 更多