--
layout: blog
title: '使用Python進(jìn)行3DES加密-pyDes'
date: 2017-06-01 12:11:34
categories: blog
tags: code
image: ''
lead-text: 'Python利用pyDes進(jìn)行3DES加密'
選擇PyDes
在進(jìn)行請(qǐng)求前使用3DES進(jìn)行加密獲取一個(gè)加密后的code添加到請(qǐng)求頭,為了方便,不用每次跑程序就寫了一個(gè)簡(jiǎn)單的</br>
利用Python進(jìn)行3DES加密的東西,說(shuō)起來(lái)簡(jiǎn)單,最后頁(yè)只有一點(diǎn)點(diǎn)代碼,不過(guò)在找到合適的加密方法,以及計(jì)算出和</br>
和Java代碼一樣的結(jié)果前花了很多時(shí)間。其中使用了包括 M2Crypto 和 Crypto這樣的庫(kù),不過(guò)沒(méi)有得到正確的結(jié)果- -。</br>最后使用PyDes中的獲得了正確的東西。
代碼
#!/usr/bin/env python
# encoding=utf-8
import base64
import hashlib
import os
import pyDes
import sys
global secret_key
secret_key = ""
param_dict = {}
param_array = []
def get_key():
return '234567892345678923456789'
pass
def get_text(params=[]):
result = ""
for param in params:
result += param
pass
pass
def get_text(params={}):
result = ""
for (k, v) in params:
result += v
pass
pass
def encrypt(key="", text=""):
if text is None:
text = ""
print "加密字符串為空,請(qǐng)確保文件格式"
return
pass
print '加密字符串:', text
print '密鑰:', key
k = pyDes.triple_des(key, pyDes.ECB, IV=None, pad=None, padmode=pyDes.PAD_PKCS5)
d = k.encrypt(text)
res = base64.standard_b64encode(d)
# 替換空格和換行
res.replace("\n", "")
res.replace("\t", "")
res.replace("\r\n", "")
res.strip("\n")
print 'validatecode:', to_md5(res).upper()
def to_md5(src=""):
m2 = hashlib.md5()
m2.update(src)
return m2.hexdigest()
def parse_file(file_content=""):
global secret_key
lines = file_content.split("\n")
# print "分解行:", lines
for line in lines:
if line.startswith("#"):
continue
pass
line_array = line.split(":")
if len(line_array) == 1:
secret_key = line
pass
elif len(line_array) == 2:
k = line_array[0]
value = line_array[1]
k.replace("\r\n", "")
value.replace("\r\n","")
param_dict[k] = value
param_array.append(value)
pass
# print line
# print param_dict
def create_param_string(dic):
param_string = ""
for k in dic:
param_string += k
pass
return param_string
pass
if __name__ == "__main__":
# 獲取參數(shù)
vars = sys.argv
if len(vars) == 2:
v = vars[1]
if v == '--help':
print "添加 -f 參數(shù)添加文件絕對(duì)路徑"
print "文件格式 # 表示注釋"
print "如果只有一行,那么表示加密的密鑰(key)"
print "參數(shù)行,形式如字典格式 key:value"
print "例子:"
print "python validate.py -f /usr/a.txt"
pass
elif len(vars) == 3:
if vars[1] == "-f":
file_path = vars[2]
file_exist = os.path.exists(file_path)
if file_exist:
file = open(file_path, 'r')
file_content = file.read()
# 解析參數(shù)文件
parse_file(file_content)
param_string = create_param_string(param_array)
encrypt(secret_key, param_string)
# print "讀取文件:\n", file_content
pass
else:
print "文件不存在!"
pass
else:
pass
上面的代碼比較簡(jiǎn)單,讀取一個(gè)文本文件中的內(nèi)容,獲取到一個(gè)數(shù)組,將數(shù)組進(jìn)行拼接,拼接后的字符串</br>
加密就好了,核心就是利用 pyDes.triple_des() 進(jìn)行加密,之后利用獲取的base64字符串去掉空格和換行</br>
去掉換行和空格這個(gè)算事重要的點(diǎn),容易忘記,最后再做一次md5轉(zhuǎn)換</br>
總結(jié)
具體的原理不太清楚,比較麻煩的點(diǎn)是triple_des轉(zhuǎn)換,然后base64,然后md5,重要的是去除空格和換行,</br>
項(xiàng)目中iOS的代碼由于沒(méi)有進(jìn)行去除空格和換行導(dǎo)致在字符串比較多的時(shí)候產(chǎn)生了和Java不同的加密結(jié)果