项目的MQTT传送的消息经过DES加密,在测试过程中,为了实现大批量模拟数据传输,编写工具。因为对Java不熟悉,故选择python。
private static byte[] encrypt(byte[] data) {
try {
byte[] key = secretKey.getBytes();
IvParameterSpec iv = new IvParameterSpec(key);
DESKeySpec desKey = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
return cipher.doFinal(data);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
首先需要pip install pydes模块
然后运行下面代码即可
#-*- coding:utf-8 -*-
import sys
import base64
from pyDes import *
from importlib import reload
reload(sys)
registration = b"2 00:00:00:00:00:00 mqtt-client ep=00:00:00:00:00:00&ip=192.168.1.1 xxxx>"
deregistration = b"1 00:00:00:00:00:00 mqtt-client"
KEY = b"test_key" #Key
IV = KEY #
k = des(KEY, CBC, IV, pad=None, padmode=PAD_PKCS5)
#encrypt
enRegist = k.encrypt(registration)
print(base64.b64encode(enRegist))#转base64编码返回
enDeregist=k.encrypt(deregistration)
print(base64.b64encode(enDeregist))
#print("d is: ", d)
#decrypt
#print("Decrypted: %r" % k.decrypt(d))