当前位置: 首页 > 工具软件 > pyDES > 使用案例 >

python3使用pyDes模块实现Java DES加密

公冶昆杰
2023-12-01

背景:

项目的MQTT传送的消息经过DES加密,在测试过程中,为了实现大批量模拟数据传输,编写工具。因为对Java不熟悉,故选择python。

源码

Java

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;
    }

python

首先需要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))

 

 

 

 

 

 类似资料: