1. 程式人生 > 實用技巧 >Asp.NetCore Web開發之路由

Asp.NetCore Web開發之路由

一、加密

1.python2加密的時候使用str,加密後的資料也是str。

>>> import base64
>>> url = "https://www.baidu.com?a=23&b=中國"
>>> b=base64.b64encode(url.decode('utf8').encode('utf-8'))
>>> type(b)
<type 'str'>
>>> import sys
>>> sys.getdefaultencoding()
'ascii'

>>> b=base64.b64encode(url.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 29: ordinal not in range(128)

對加密的str,編碼後,再使用base64加密,報錯。why?

首先:

在python2中,字串str預設採用的是ASCII編碼。

因此在base64加密的時候,直接使用ascii的字串str,加密即可。返回字串str。

其次:

在python2中,使用unicode型別作為編碼的基礎型別。即

decode encode

str ---------> unicode --------->str

因此,如果要使用unicode,進行base64加密。

可以有兩種方法,是正確的:

1.按照上面的步驟,先decode,再encode,這個時候字串是預設的ascii。

>>> b=base64.b64encode(url.decode('utf8').encode('utf-8'))
>>> type(b)
<type 'str'>

2.將系統編碼設定為utf8,直接encode()

>>> sys.getdefaultencoding()
'ascii'
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf8')
>>> b=base64.b64encode(url.encode('utf-8'))
>>> type(b)
<type 'str'>
>>> sys.getdefaultencoding()
'utf8'

2.python3的字串在base64加密前,必須先編碼為二進位制。

>>> import base64
>>> url = "https://www.baidu.com?a=23&b=中國"
>>> b=base64.b64encode(url.encode('utf-8'))
>>> type(b)
<class 'bytes'>

否則,丟擲異常

>>> 
>>> b=base64.b64encode(url)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

我們可以檢視一下python3預設使用的編碼

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

總結:

  • 在python3,base64加密前,必須先編碼為bytes。
  • 在python2,可能會混淆。因此:
    • 不管系統編碼為預設的ascii,還是已經改為utf8。先decode,再encode始終不會錯。

      b=base64.b64encode(url.decode('utf-8').encode('utf-8'))

    • 如果可以全域性確認,python2的系統編碼始終是預設的ascii。就直接base64加密即可。

    • 如果可以全域性確認,python2的系統編碼始終是預設的utf8。base64加密前,必須先encode。