当前位置: 首页>>代码示例>>Python>>正文


Python simplecrypt.encrypt函数代码示例

本文整理汇总了Python中simplecrypt.encrypt函数的典型用法代码示例。如果您正苦于以下问题:Python encrypt函数的具体用法?Python encrypt怎么用?Python encrypt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了encrypt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_bytes_password

 def test_bytes_password(self):
     ptext = decrypt(b'password', encrypt(b'password', b'message'))
     assert ptext == b'message', ptext
     ptext = decrypt('password', encrypt(b'password', b'message'))
     assert ptext == b'message', ptext
     ptext = decrypt(b'password', encrypt('password', b'message'))
     assert ptext == b'message', ptext
开发者ID:italianpride15,项目名称:blueconnect-gae,代码行数:7,代码来源:tests.py

示例2: save_db

def save_db(creds, password=''):
  creds['password'] = password and hexlify(encrypt(password, creds['password'])) or creds['password']
  creds['username'] = password and hexlify(encrypt(password, creds['username'])) or creds['username']
  keychain = Keychain()
  account = getlogin()
  password = "%s%s%s" % (creds['username'], JOIN_STRING, creds['password'])
  return keychain.set_generic_password(KEYCHAIN, account, password, SERVICE_NAME)
开发者ID:schwark,项目名称:alfred-alarmcom,代码行数:7,代码来源:list_collector.py

示例3: config_taskstore

def config_taskstore():
    if len(sys.argv) < 5:
        print('''Usage for configure taskstore.ini for database connection:
            python taskstore.py host user password database
            python taskstore.py host user password database encrypt_key

            Example:
                python taskstore.py 172.16.16.16 root xFGt3Swq test
                (Encrypt key will be taken from environment)
                python taskstore.py 172.16.16.16 root xFGt3Swq test MyEncrYptKey
                (Encrypt key taken from param)
              ''')
        sys.exit(1)
    host = sys.argv[1]
    user = sys.argv[2]
    password = sys.argv[3]
    db = sys.argv[4]
    if len(sys.argv) == 5:
        secret = os.getenv('SECRET_KEY', 'my_secret_key') #get secret from env
    else:
        secret = sys.argv[5] #get secret by param
    current_path = os.path.dirname(os.path.realpath(__file__))
    newfile = os.path.join(current_path, 'taskstore.ini')
    with open(newfile, 'w') as f:
        f.write('[db_connection]\n')
        f.write('host='+base64.b64encode(encrypt(secret, host))+'\n')
        f.write('user='+base64.b64encode(encrypt(secret, user))+'\n')
        f.write('password='+base64.b64encode(encrypt(secret, password))+'\n')
        f.write('db='+base64.b64encode(encrypt(secret, db)))
        print('done')
开发者ID:ivandavid77,项目名称:wa_worker,代码行数:30,代码来源:taskstore.py

示例4: test_unicode_plaintext

 def test_unicode_plaintext(self):
     ptext = decrypt(u'password', encrypt(u'password', u'message'))
     assert ptext.decode('utf8') == 'message', ptext
     ptext = decrypt(u'password', encrypt(u'password', u'message'.encode('utf8')))
     assert ptext == 'message'.encode('utf8'), ptext
     ptext = decrypt(u'password', encrypt(u'password', u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹'))
     assert ptext.decode('utf8') == u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹', ptext
     ptext = decrypt(u'password', encrypt(u'password', u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹'.encode('utf8')))
     assert ptext == u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹'.encode('utf8'), ptext
开发者ID:d10n,项目名称:simple-crypt,代码行数:9,代码来源:tests.py

示例5: right

def right():
    plaintext = 'hello world'

    key = 'python'
    ciphertext = encrypt(key, plaintext)
    print ciphertext

    key = 'password'
    ciphertext = encrypt(key, plaintext)
    print ciphertext

    plaintext = decrypt(key, ciphertext)
    print plaintext
开发者ID:EmuxEvans,项目名称:py_learn,代码行数:13,代码来源:simple_crypt.py

示例6: send_broadcast

def send_broadcast(request):
    if request.method == 'POST':
        form = BroadcastForm(request.POST)

        # validation checking...
        if form.is_valid():
            sender = request.user

            subject = request.POST['subject']
            text = request.POST['body']
            encrypted = request.POST.get('encrypted', False)
            enc_key = request.POST['enc_key']
            raw_b = b""

            if enc_key == "":
                enc_key = "N/A"
            else:

                #encrypt
                #encrypt
                raw_b = encrypt(enc_key, text)
                text=str(raw_b)

            pm_broadcast(sender,"", subject, encrypted, raw=raw_b, body=text)
            return render(request, 'postman/inbox.html', )
        else:
            return render(request, 'broadcast.html', {'message_form': form})


    else:
        form = BroadcastForm()
        return render(request, 'broadcast.html', {'message_form': form})
开发者ID:mcr5fh,项目名称:Django_WebProject,代码行数:32,代码来源:views.py

示例7: post

    def post(self):
        auth_code = self.request.get('code')
        auth_header = "Basic " + base64.b64encode(k_client_id + b":" + k_client_secret)
        params = {
            "grant_type": "authorization_code",
            "redirect_uri": k_client_callback_url,
            "code": auth_code
        }
        encoded_params = urllib.urlencode(params)

        response = urlfetch.fetch(url=k_spotify_accounts_endpoint + "/api/token",
                                  payload=encoded_params,
                                  method=urlfetch.POST,
                                  headers={"Authorization": auth_header},
                                  validate_certificate=True)

        if response.status_code == 200:
            token_data = json.loads(response.content)
            refresh_token = token_data["refresh_token"]
            encrypted_token = simplecrypt.encrypt(k_encryption_secret, refresh_token)
            base64_encrypted_token = base64.encodestring(encrypted_token)
            token_data["refresh_token"] = base64_encrypted_token
            response.content = json.dumps(token_data)

        self.response.headers.add_header("Access-Control-Allow-Origin", '*')
        self.response.headers['Content-Type'] = 'application/json'
        self.response.status = response.status_code
        self.response.write(response.content)
开发者ID:chrismlarson,项目名称:spotify-token-swap-gae,代码行数:28,代码来源:main.py

示例8: click_save

 def click_save(self):
     raw_text = self.textEdit.toPlainText()
     t=unicode(raw_text)
     ciphertext = encrypt('123', t)
     self.content.text = hexlify(ciphertext)
     self.content.save()
     self.textEdit.clear
开发者ID:gpertaia,项目名称:crypto-diary,代码行数:7,代码来源:TextContent.py

示例9: dataproxy_resource_update

def dataproxy_resource_update(context, data_dict=None):
    """
    Intercepts default resource_update action and encrypts password for dataproxy type resources
    Args:
        context: Request context.
        data_dict: Parsed request parameters.
    Returns:
        see get_action('resource_update').
    Raises:
        Exception: if ckan.dataproxy.secret configuration not set.
    """
    #If not set, default to empty string
    data_dict['url_type'] = data_dict.get('url_type', '')
    url_type = data_dict['url_type']

    if url_type == 'dataproxy':
        secret = config.get('ckan.dataproxy.secret', False)
        if not secret:
            raise Exception('ckan.dataproxy.secret must be defined to encrypt passwords')
        #replace password with a _password_ placeholder
        password = data_dict.get('db_password', '')
        if password == '':
            #we don't want to overwrite existing password with empty string
            resource = Resource.get(data_dict['id'])
            data_dict['db_password'] = resource.extras['db_password']
        else:
            data_dict['url'] = data_dict['url'].replace(password, '_password_')
            #encrypt db_password
            data_dict['db_password'] = hexlify(encrypt(secret, password))

    site_url = config.get('ckan.site_url', '127.0.0.1')
    data_dict['url'] = '{0}/api/3/action/datastore_search?resource_id={1}&downloaded=true'.format(site_url, data_dict['id'])

    return orig_resource_update(context, data_dict)
开发者ID:oepdtt,项目名称:ckanext-dataproxy,代码行数:34,代码来源:update.py

示例10: main

def main(key, password):
    print 'Uses aes encryption'
    print 'Key: %s Password: %s' % (key, password)
    encrypt_one = encrypt(key, password)  # python string
    encrypt_two = encrypt(key, unicode(password))  # unicode
    encrypt_three = encrypt(key, password.encode('utf8'))  # utf8
    print 'encrypt_one: %s' % hexlify(encrypt_one)
    print 'encrypt_twp: %s' % hexlify(encrypt_two)
    print 'encrypt_three: %s' % hexlify(encrypt_three)
    print '\nEven though the key and password are the same'
    print 'Encoding matters'
    print 'encrypt_one == encrypt_two', encrypt_one == encrypt_two
    print 'encrypt_one == encrypt_three', encrypt_one == encrypt_three
    print 'encrypt_two == encrypt_three', encrypt_two == encrypt_three
    print '\nThe following will be the same for all 3'
    print 'plaintext: %s' % decrypt(key, encrypt_one)
开发者ID:Devon-Peroutky,项目名称:OneDir,代码行数:16,代码来源:sc_demo.py

示例11: submitEmailPassword

def submitEmailPassword():

    for k in request.forms.keys():
        print k, request.forms[k]

    username = request.forms.get('email')
    password = request.forms.get('password')

    password_hashed = base64.urlsafe_b64encode(pbkdf2_sha256.encrypt(password, rounds=NOF_HASH_ROUNDS, salt_size=16))

    username_encrypted = base64.urlsafe_b64encode(encrypt(ENCRYPTION_PASSWORD, username))

    usersTable = db.table('users')

    existingUser = usersTable.search(where('key') == username_encrypted)
    if existingUser:
        if pbkdf2_sha256.verify(existingUser['values']['password'],password_hashed):
            pass
        else:
            print "wrong login"
    else:
        usersTable.insert({'key':username_encrypted, 'values':{'password':password_hashed}})
        videosTable = db.table('videos')
        existing_cookie = request.get_cookie('sebifyme',secret=GLOBAL_COOKIE_SECRET)
        uid = existing_cookie['uid']
        elements = videosTable.search((where('values').has('uploaded_by_uid') == uid) & (where('values').has('uploaded_by_user') == None))
        for el in elements:
            currentValues = el['values']
            currentValues['uploaded_by_user'] = username_encrypted
            videosTable.update({'values':currentValues}, eids=[el.eid])

    website_content = template('video',video_name='joke.mp4')

    return website_content
开发者ID:dbaclin,项目名称:sebifymewebsite,代码行数:34,代码来源:site.py

示例12: create_config

def create_config(project_dir, encrypt_pass='None'):

    config_dir = '%s/.config' % project_dir
    f = open(config_dir, 'w')

    print
    print '------Welcome to DataTools Configuration---------'
    print
    print 'Select SQL Flavor'
    print '[1] - SQLite'
    print '[2] - MySQL'
    flavor = int(raw_input('Input Number: '))
    print

    if flavor == 1:

        info = 'sqlite'
        info += ':%s.db' % raw_input('Database Name: ')

    elif flavor == 2:

        info = 'mysql'
        info += ':%s' % raw_input('Host: ')
        info += ':%s' % raw_input('Username: ')
        info += ':%s' % raw_input('Password: ')
        info += ':%s' % raw_input('Database Name: ')

    print
    print 'Encrypting Config File'
    f.write(encrypt(encrypt_pass, info))
    print 'Config File Complete'
开发者ID:rosspalmer,项目名称:DataTools,代码行数:31,代码来源:project.py

示例13: encrypt_fn

def encrypt_fn(destroy_this):
    password = password_var_enc.get()
    password_conf = password_var_con.get()

    if password == password_conf:


        ciphertext = encrypt(password, private_key_readable)

        pem_file = open("privkey_encrypted.der", 'wb')
        pem_file.write(base64.b64encode(ciphertext))
        pem_file.close()

        encrypt_b.configure(text="Encrypted", state=DISABLED)
        destroy_this.destroy()
        os.remove("privkey.der")
        lock_b.configure(text="Lock", state=NORMAL)
    else:
        mismatch = Toplevel()
        mismatch.title("Bismuth")

        mismatch_msg = Message(mismatch, text="Password mismatch", width=100)
        mismatch_msg.pack()

        mismatch_button = Button(mismatch, text="Continue", command=mismatch.destroy)
        mismatch_button.pack(padx=15, pady=(5, 5))
开发者ID:zhilinwww,项目名称:Bismuth,代码行数:26,代码来源:legacy_gui.py

示例14: dataproxy_resource_create

def dataproxy_resource_create(context, data_dict=None):
    """
    Intercepts default resource_create action and encrypts password if resource is dataproxy type
    Args:
        context: Request context.
        data_dict: Parsed request parameters.
    Returns:
        see get_action('resource_create').
    Raises:
        Exception: if ckan.dataproxy.secret configuration not set.
    """
    #If not set, default to empty string
    url_type = data_dict.get('url_type')

    if url_type == 'dataproxy':
        secret = config.get('ckan.dataproxy.secret', False)
        if not secret:
            raise Exception('ckan.dataproxy.secret must be defined to encrypt passwords')
        password = data_dict.get('db_password')
        #replace password with a _password_ placeholder
        data_dict['url'] = 'tmpURL' #data_dict['url'].replace(password, '_password_')
        #encrypt db_password
        data_dict['db_password'] = hexlify(encrypt(secret, password))

    data_dict = orig_resource_create(context, data_dict)

    site_url = config.get('ckan.site_url', '127.0.0.1')
    data_dict['url'] = '{0}/api/3/action/datastore_search?resource_id={1}&downloaded=true'.format(site_url, data_dict['id'])

    return orig_resource_update(context, data_dict)
开发者ID:oepdtt,项目名称:ckanext-dataproxy,代码行数:30,代码来源:create.py

示例15: createorder

def createorder(myidhash, mybtc, offer, cryptkey, tx_fee, retries=0):
    price = decimal.Decimal(offer.obj['price'])
    try:
        pubkey = btcd.validateaddress(mybtc)['pubkey']
        multisig = btcd.createmultisig( 2, sorted([offer.obj['pubkey'], pubkey]) )
        change_addr = btcd.getrawchangeaddress()
    except httplib.BadStatusLine:
        reconnect_btcd(retries)
        return createorder(myidhash, mybtc, offer, cryptkey, tx_fee, retries+1)
    
    def create_funding(fee, retries=0):
        rawtx_hex = mktx(price, multisig['address'], change_addr, fee)
        try:
            return btcd.signrawtransaction(rawtx_hex)['hex']
        except httplib.BadStatusLine:
            reconnect_btcd(retries)
            return create_funding(fee, retries+1)
    
    signedtx_hex = create_funding(tx_fee)
    crypttx = base64.b64encode( simplecrypt.encrypt(cryptkey, signedtx_hex) )
    
    try:
        signedtx = btcd.decoderawtransaction(signedtx_hex)
    except httplib.BadStatusLine:
        reconnect_btcd(retries)
        return createorder(myidhash, mybtc, offer, cryptkey, tx_fee, retries+1)
    
    vout = searchtxops(signedtx, multisig['address'], price)
    
    return createordermsgstr(mybtc, offer.hash, offer.obj['vendorid'], myidhash, \
                                        pubkey, multisig, crypttx, signedtx['txid'], \
                                        vout, signedtx['vout'][vout]['scriptPubKey']['hex'] )
开发者ID:metamarcdw,项目名称:metamarket,代码行数:32,代码来源:MM_util.py


注:本文中的simplecrypt.encrypt函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。