有些时候我们不得不在自己的代码里写上密码,为了安全起见,我们可以为自己的密码加密
先上段代码,这个代码是转自网上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
root@ProFtp: / usr / lib / python2. 7 # more jastmencrypt.py """ jastme encrypt password """ def encrypt(key, s): b = bytearray( str (s).encode( "gbk" )) n = len (b) # 求出 b 的字节数 c = bytearray(n * 2 ) j = 0 for i in range ( 0 , n): b1 = b[i] b2 = b1 ^ key # b1 = b2^ key c1 = b2 % 16 c2 = b2 / / 16 # b2 = c2*16 + c1 c1 = c1 + 65 c2 = c2 + 65 # c1,c2都是0~15之间的数,加上65就变成了A-P 的字符的编码 c[j] = c1 c[j + 1 ] = c2 j = j + 2 return c.decode( "gbk" ) def decrypt(key, s): c = bytearray( str (s).encode( "gbk" )) n = len (c) # 计算 b 的字节数 if n % 2 ! = 0 : return "" n = n / / 2 b = bytearray(n) j = 0 for i in range ( 0 , n): c1 = c[j] c2 = c[j + 1 ] j = j + 2 c1 = c1 - 65 c2 = c2 - 65 b2 = c2 * 16 + c1 b1 = b2^ key b[i] = b1 try : return b.decode( "gbk" ) except : return "failed" |
以UTF8的编码保存这个代码到/usr/lib/python2.7
1
2
3
4
5
6
7
|
In [ 1 ]: import jastmencrypt In [ 3 ]: jastmencrypt.encrypt( 119 , 'mypassword' ) 加密 Out[ 3 ]: u 'KBOAHAGBEAEAAAIBFADB' In [ 4 ]: jastmencrypt.decrypt( 119 , 'KBOAHAGBEAEAAAIBFADB' ) 解密 Out[ 4 ]: u 'mypassword' |
我们在ipython中先加密好密码,然后拿到代码里,要使用的时候解密一下即可,这样可以很大程度上保证我们的密码安全。
以上就是本文给大家分享的全部内容了,希望对大家学习Python代码能够有所帮助。