2011-09-04 71 views
2

我將開發基於CherryPy的Web應用程序。這將是一個應用程序,公共用戶可以註冊並在之後登錄 - 通常的東西。像Rails和Django這樣的其他框架包含有關安全性的複雜代碼:加密密碼和醃製密碼,防止會話劫持,...... CherryPy中是否有類似的功能?到目前爲止我只找到非常簡單的解決方案!?CherryPy中的用戶管理

回答

1

我使用了這個認證示例,其中包括修復註釋。

http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions

下面是如何加密

import Crypto.Random 
from Crypto.Cipher import AES 
import hashlib 

# salt size in bytes 
SALT_SIZE = 16 

# number of iterations in the key generation 
NUMBER_OF_ITERATIONS = 20 

# the size multiple required for AES 
AES_MULTIPLE = 16 


__all__ = ['Encryption'] 

class Encryption(object): 
    def generate_key(self, password, salt, iterations): 
     assert iterations > 0  
     key = password + salt  
     for i in range(iterations): 
      key = hashlib.sha256(key).digest() 

    return key 

    def pad_text(self, text, multiple): 
     extra_bytes = len(text) % multiple  
     padding_size = multiple - extra_bytes  
     padding = chr(padding_size) * padding_size  
     padded_text = text + padding 

     return padded_text 

    def unpad_text(self, padded_text): 
     padding_size = padded_text[-1]  
     text = padded_text[:-padding_size] 

     return text 


    def encrypt(self, plaintext, password): 
     salt = Crypto.Random.get_random_bytes(SALT_SIZE)  
     key = Encryption.generate_key(self, password, salt, NUMBER_OF_ITERATIONS)  
     cipher = AES.new(key, AES.MODE_ECB)  
     padded_plaintext = Encryption.pad_text(self, plaintext, AES_MULTIPLE)  
     ciphertext = cipher.encrypt(padded_plaintext)  
     ciphertext_with_salt = salt + ciphertext 

     return ciphertext_with_salt 

然後調用加密功能

encryptedPassword = Encryption.encrypt(self, Password, bytes(cherrypy.request.app.config['Encryption']['Password'], 'UTF-8')) 

希望這有助於!

Andrew