应用中经常用pyCrypto 来生成用户Token等相关信息,够简单,所以贴代码分享
部分代码被关闭或者打开,使用者请自行调整,如果了解rsa很简单理解一下代码
1 GCONFS={
2 'auth_public_keyfile':'public.rsa',
3 'auth_private_keyfile':'private.rsa'
4 }
5
6
7 def encrypt_des(key,text):
8 from Crypto.Cipher import DES
9 import base64
10 from Crypto import Random
11 #iv = Random.get_random_bytes(8)
12 des = DES.new(key, DES.MODE_ECB)
13 reminder = len(text)%8
14 if reminder ==0: # pad 8 bytes
15 text+='\x08'*8
16 else:
17 text+=chr(8-reminder)* (8-reminder)
18 #text+=' '*(8-len(text)%8)
19 return des.encrypt(text)
20 #return base64.encodestring(des.encrypt(text))
21
22 def decrypt_des(key,text):
23 from Crypto.Cipher import DES
24 import base64
25 # print key
26 des = DES.new(key, DES.MODE_ECB)
27 text = des.decrypt(text)
28 pad = ord(text[-1])
29 if pad == '\x08':
30 return text[:-8]
31 return text[:-pad]
32
33
34 def rsa_generate():
35 from Crypto.PublicKey import RSA
36 from Crypto import Random
37 random_generator = Random.new().read
38 key = RSA.generate(1024, random_generator)
39
40
41 #print key.publickey().encrypt('123213213123213213',20)
42 public = key.publickey().exportKey()
43 #print key.publickey().exportKey()
44 private = key.exportKey()
45 return public,private
46
47 def rsa_encrypt(key,text):
48 '''
49 传入私钥key和待加密明文数据text
50 自动生成8字节长度随机密码P,用P将text进行des加密生成E,
51 用私钥key加密P生成P2
52
53 key - private key
54 text - orignal text
55 @return: [P2+E] RSA加密的des秘钥 + 加密的密文
56 '''
57 import uuid
58 from Crypto.PublicKey import RSA
59 deskey = hashlib.md5(uuid.uuid1().hex).hexdigest()[:8]
60 text = encrypt_des(deskey,text)
61
62 key = RSA.importKey(key)
63 r = key.encrypt(deskey,32)
64
65 return r[0]+text # 加密的key,和des加密的数据
66
67 def rsa_decrypt(key,text):
68 from Crypto.PublicKey import RSA
69 try:
70 rsa = RSA.importKey(key)
71 deskey = text[:128]
72 text = text[128:]
73 deskey = rsa.decrypt(deskey)
74 return decrypt_des(deskey,text)
75 except:
76 return ''
77
78 class Cipher:
79 def __init__(self):
80 # self.pubkey = pubkey
81 # self.privkey = privkey
82 pass
83
84 def encrypt(self,key,text):
85 return rsa_encrypt(key,text)
86
87
88 def decrypt(self,key,text):
89 return rsa_decrypt(key,text)
90
91 @staticmethod
92 def getCipher():
93 try:
94 cip = Cipher()
95 return cip
96 except:
97 traceback.print_exc()
98 return None
99
100 def encryptToken(user):
101 '''
102 用户信息转换为token
103 '''
104 token=''
105 try:
106 d = json.dumps(user)
107 # f = open(GCONFS['auth_public_keyfile'],'r')
108 # pubkey = f.read()
109 # f.close()
110 pubkey = ENCRYPT_PUBKEY
111 # d = Cipher.getCipher().encrypt(pubkey,d) #rsa encrpyt
112 token = base64.encodestring(d).strip()
113 #print 'token size:',len(token)
114 except:
115 print traceback.format_exc()
116 token = ''
117
118 return token
119
120 def decryptToken(token):
121 user = None
122 try:
123 # f = open(GCONFS['auth_private_keyfile'],'r')
124 # privkey = f.read()
125 # f.close()
126 privkey = ENCRYPT_PRIVKEY
127 d = base64.decodestring(token)
128 # d = Cipher.getCipher().decrypt(privkey,d) #rsa decrept
129 user = json.loads(d)
130 except:
131 #print traceback.format_exc()
132 pass
133 return user