日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python常用库之base64

發布時間:2025/7/14 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python常用库之base64 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

1. 什么是base64

base64是一種將不可見字符轉換為可見字符的編碼方式。

?

2. 如何使用

最簡單的使用方式

import base64if __name__ == '__main__':s = 'plain text'# base64編碼t = base64.b64encode(s.encode('UTF-8'))print(t)# base64解碼t = base64.b64decode(t)print(t)# base32編碼t = base64.b32encode(s.encode('UTF-8'))print(t)# base32解碼t = base64.b32decode(t)print(t)# base16編碼t = base64.b16encode(s.encode('UTF-8'))print(t)# base16解碼t = base64.b16decode(t)print(t)

base64.bxxencode接受一個字節數組bytes用于加密,返回一個bytes存儲加密之后的內容。

base64.bxxdecode接受一個存放著密文的bytes,返回一個bytes存放著解密后的內容。

?

對URL進行編碼

編碼之后的+和/在請求中傳輸的時候可能會出問題,使用urlsafe_b64encode方法會自動將:

+映射為- /映射為_

這樣加密之后的就都是在網絡上傳輸安全的了。

import base64if __name__ == '__main__':s = 'hello, world't = base64.urlsafe_b64encode(s.encode('UTF-8'))print(t)t = base64.urlsafe_b64decode(t)print(t)

使用urlsafe_b64encode相當于是base64.b64encode(s.encode('UTF-8'), b'-_'),第二個參數指定了使用哪兩個字符來替換掉+和/:

import base64if __name__ == '__main__':s = 'hello, world't = base64.b64encode(s.encode('UTF-8'), b'-_')print(t)t = base64.b64decode(t, b'-_')print(t)

?

直接對流進行編碼

加密和解密的時候可以直接傳入一個流進去,base64模塊加密方法會從輸入流中讀取數據進行加密,同時將結果寫到輸出流中。

import base64 from io import BytesIOif __name__ == '__main__':input_buff = BytesIO()output_buff = BytesIO()input_buff.write(b'hello, world')input_buff.seek(0)base64.encode(input_buff, output_buff)s = output_buff.getvalue()print(s)

?

參考資料:

1. https://docs.python.org/3.5/library/base64.html

轉載于:https://www.cnblogs.com/cc11001100/p/7789270.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的python常用库之base64的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。