繁体   English   中英

在Python代码中设置非人类可读的Gmail密码

[英]Make non-human readable gmail password in python code

我有以下代码:

username = 'username@gmail.com'
password = 'password'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)

我正在寻找一种不对密码进行硬编码的方法。 GETPASS需要交互式输入密码提示,我不希望这样。 是否有其他方法可以实现这一目标?

提前致谢

有很多混淆或加密的方法,但是您将遇到的问题是,无论它是什么,如果它在您的代码中,那么有权访问您的代码并可以读取它的人可以对其进行解密。

我建议以加密后再以base64编码的形式将其存储在数据库中。 基本而言,Base64编码将意味着您不会遇到数据库可能遇到的任何怪异字符。

这是一个例程,它将在AES中为您加密和解密内容

import base64
from Crypto.Cipher import AES

key ="" # ASSIGN 32 ALPHANUMERIC CHARACTERS TO THIS VAR
iv = "" # ASSIGN 16 ALPHANUMERIC CHARACTERS TO THIS VAR
def enCrypt(string):
    """
    Encypts in AES 256bit and then base64 encodes it for database entry
    """
    encFormat = AES.new(key, AES.MODE_CFB, iv)
    return base64.b64encode(encFormat.encrypt(string))
def deCrypt(string):
    """
    Decodes the string fron base64 then decrypt the resulting AES string
    """
    destring = base64.b64decode(string)
    encFormat = AES.new(key, AES.MODE_CFB, iv)
    return encFormat.decrypt(destring)

这很容易解释,但是如果您有密码,例如“ bobbins”

encrypted = enCrypt("bobbins")

并解密

deCrypt(encrypted)

但是,我强烈建议将其存储在数据库中,即使它很小而基本,例如sqlite。 为此,我建议您查看SQLAlchemy模块

私钥,公钥尝试如何?

用您的公共密钥加密密码,并将其硬编码写入程序中。 将私钥保存在计算机上定义的某个位置(不提交或共享任何形式)。 然后,要使用该程序登录,请使用私钥对密码进行加密。

它只能在您的PC(具有私钥的地方)上工作,但也许就足够了。

看看PyCrypto: https ://pythonhosted.org/pycrypto/

这一切都取决于您在这里得到的信息–如果只是不想共享密码,您可以设置“特定于应用程序的”密码,但是仍然允许其他人访问您的帐户…

OAuth允许您设置范围,以便具有“密码”的人可以发送电子邮件,但不能访问其他帐户活动,甚至不能阅读邮件,这取决于您的意愿。

如果您未设置SMTP,则Google每天会通过GMail API允许1,000,000,000个“配额单位”。

GMail Python API

初始化服务

您可以使用OAuth身份验证来允许通过https://www.googleapis.com/auth/gmail.sendscope ”发送电子邮件。

如果您决定使用这条路线(也许使用python库) ,则应该能够使用Google的示例发送消息:

传送讯息

"""Send an email message from the user's account.
"""

import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os

from apiclient import errors


def SendMessage(service, user_id, message):
  """Send an email message.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    message: Message to be sent.

  Returns:
    Sent Message.
  """
  try:
    message = (service.users().messages().send(userId=user_id, body=message)
               .execute())
    print 'Message Id: %s' % message['id']
    return message
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


def CreateMessage(sender, to, subject, message_text):
  """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.

  Returns:
    An object containing a base64url encoded email object.
  """
  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string())}


def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir,
                                filename):
  """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.
    file_dir: The directory containing the file to be attached.
    filename: The name of the file to be attached.

  Returns:
    An object containing a base64url encoded email object.
  """
  message = MIMEMultipart()
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject

  msg = MIMEText(message_text)
  message.attach(msg)

  path = os.path.join(file_dir, filename)
  content_type, encoding = mimetypes.guess_type(path)

  if content_type is None or encoding is not None:
    content_type = 'application/octet-stream'
  main_type, sub_type = content_type.split('/', 1)
  if main_type == 'text':
    fp = open(path, 'rb')
    msg = MIMEText(fp.read(), _subtype=sub_type)
    fp.close()
  elif main_type == 'image':
    fp = open(path, 'rb')
    msg = MIMEImage(fp.read(), _subtype=sub_type)
    fp.close()
  elif main_type == 'audio':
    fp = open(path, 'rb')
    msg = MIMEAudio(fp.read(), _subtype=sub_type)
    fp.close()
  else:
    fp = open(path, 'rb')
    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    fp.close()

  msg.add_header('Content-Disposition', 'attachment', filename=filename)
  message.attach(msg)

  return {'raw': base64.urlsafe_b64encode(message.as_string())}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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