1. 程式人生 > >Python Base64轉碼解碼

Python Base64轉碼解碼

Python Base64 提供了好幾種方法例如:
encode,
decode,

encodestring,
decodestring,

b64encode,
b64decode,

standard_b64encode
standard_b64decode

urlsafe_b64decode,
urlsafe_b64encode。

  1. encode, decode
    用來轉碼和 解碼檔案的,也可以對StringIO裡的資料做編解碼

    
    #讀取檔案進行編碼
    
    inputRead = open('/Users/Mr_Chen/Desktop/test.jpeg','rb')
    outputWrit = open('/Users/Mr_Chen/Desktop/testEncode.txt'
    ,'wb') #編碼檔案 base64Test = base64.encode(inputRead,outputWrit) #讀取檔案後進行解碼 inputRead = open('/Users/Mr_Chen/Desktop/testEncode.txt','rb') outputWrit = open('/Users/Mr_Chen/Desktop/testDecode.jpeg','wb') #解碼檔案 base64Test2 = base64.decode(inputRead,outputWrit)
  2. encodestring, decodestring,
    對字串進行轉碼,解碼

    import
    base64 str1 = 'This is Test String' #對字串進行轉碼 enTest = base64.encodestring(str1) print '轉碼後:',enTest #對字串進行解碼 deTest = base64.decodestring(enTest) print '解碼後:',deTest
  3. b64encode,b64decode,
    (base64 模組提供了 b16encode,b16decode,b32encode,b32decode)
    用來編碼和解碼字串,並且有一個替換符號字元的功能。當base64編碼後的字元除 了英文字母和數字外還有三個字元 + / =,用提替換到 +/= 這些字元

    
    # -*- coding:utf-8 -*-
    
    import  base64
    
    
    
    #讀取檔案進行base16轉碼
    
    inputRead = open('/Users/Mr_Chen/Desktop/test.txt','rb')
    base16Test = base64.b16encode(inputRead.read())
    inputRead.close()
    print  'base16 Encode:',base16Test
    
    
    #進行base16解碼
    
    base16Test2 = base64.b16decode(base16Test)
    print 'base16 Decode:',base16Test2
    
    
    
    
    #讀取檔案進行base32轉碼
    
    inputRead2 = open('/Users/Mr_Chen/Desktop/test.txt','rb')
    base32Test = base64.b32encode(inputRead2.read())
    inputRead2.close()
    print  'base32 Encode:',base32Test
    
    
    #進行base32轉碼
    
    base32Test2 = base64.b32decode(base32Test)
    print 'base32 Decode:',base32Test2
    
    
    
    
    #讀取檔案進行base64轉碼
    
    inputRead3 = open('/Users/Mr_Chen/Desktop/test64.txt','rb')
    base64Test = base64.b64encode(inputRead3.read())
    inputRead3.close()
    print  'base64 Encode:',base64Test
    
    
    #進行base64解碼
    
    base64Test2 = base64.b64decode(base64Test)
    print 'base64 Decode:',base64Test2
  4. standard_b64encode,standard_b64decode
    進行標準的base64,同樣可以進行string ,檔案的轉碼,解碼
    使用效果和encodestring 相同

    
    # -*- coding:utf-8 -*-
    
    
    import base64
    
    text = 'This is Test String!'
    
    
    #進行轉碼
    
    baseStand = base64.standard_b64encode(text)
    print 'baseStand:',baseStand
    
    
    #進行解碼
    
    basee = base64.encodestring(text)
    print 'baseEncodeString:',basee
    
  5. urlsafe_b64decode,urlsafe_b64encode
    主要進行對url 的安全轉碼

    
    # -*- coding:utf-8 -*-
    
    
    import  base64
    
    
    text = "http://www.baidu.com"
    
    
    #baseurl Encode 轉碼
    
    baseUrl = base64.urlsafe_b64encode(text)
    print "baseUrlEncode:" ,baseUrl
    
    
    #baseurl Encode 解碼
    
    baseUrl2 = base64.urlsafe_b64decode(baseUrl)
    print "baseUrlDecode:" ,baseUrl2