首页 > 编程语言 >携程 3DES加密解密 java python

携程 3DES加密解密 java python

时间:2023-09-21 18:11:07浏览次数:49  
标签:3DES java String python encrypted hex return byte data

java

package com.example;

import org.springblade.core.tool.utils.*;

import javax.annotation.Nullable;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.util.Objects;

public class DES3 {


    public static void main(String[] args) {
        String APIId = "WHHBQT230202113010867";
        String APIKey = "02f9f24427473e7a7d2e7454660a283b";
        String str = "Hello, World!";
        String encrypted = encryptToHex(str, APIKey);
        System.out.println("encrypted to hex = " + encrypted);

        String decrypted = decryptFormHex(encrypted, APIKey);
        System.out.println(" hex  to decrypted = " + decrypted);
    }

    public static String encryptToHex(byte[] data, String password) {
        return HexUtil.encodeToString(encrypt(data, password));
    }

    @Nullable
    public static String encryptToHex(@Nullable String data, String password) {
        if (StringUtil.isBlank(data)) {
            return null;
        } else {
            byte[] dataBytes = data.getBytes(Charsets.UTF_8);
            return encryptToHex(dataBytes, password);
        }
    }

    @Nullable
    public static String decryptFormHex(@Nullable String data, String password) {
        if (StringUtil.isBlank(data)) {
            return null;
        } else {
            byte[] hexBytes = HexUtil.decode(data);
            return new String(decrypt(hexBytes, password), Charsets.UTF_8);
        }
    }

    public static String encryptToBase64(byte[] data, String password) {
        return Base64Util.encodeToString(encrypt(data, password));
    }

    @Nullable
    public static String encryptToBase64(@Nullable String data, String password) {
        if (StringUtil.isBlank(data)) {
            return null;
        } else {
            byte[] dataBytes = data.getBytes(Charsets.UTF_8);
            return encryptToBase64(dataBytes, password);
        }
    }

    public static byte[] decryptFormBase64(byte[] data, String password) {
        byte[] dataBytes = Base64Util.decode(data);
        return decrypt(dataBytes, password);
    }

    @Nullable
    public static String decryptFormBase64(@Nullable String data, String password) {
        if (StringUtil.isBlank(data)) {
            return null;
        } else {
            byte[] dataBytes = Base64Util.decodeFromString(data);
            return new String(decrypt(dataBytes, password), Charsets.UTF_8);
        }
    }

    public static byte[] encrypt(byte[] data, byte[] desKey) {
        return des(data, desKey, 1);
    }

    public static byte[] encrypt(byte[] data, String desKey) {
        return encrypt(data, ((String) Objects.requireNonNull(desKey)).getBytes(Charsets.UTF_8));
    }

    public static byte[] decrypt(byte[] data, byte[] desKey) {
        return des(data, desKey, 2);
    }

    public static byte[] decrypt(byte[] data, String desKey) {
        return decrypt(data, ((String) Objects.requireNonNull(desKey)).getBytes(Charsets.UTF_8));
    }

    private static byte[] des(byte[] data, byte[] desKey, int mode) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Cipher cipher = Cipher.getInstance("DES");
            DESKeySpec desKeySpec = new DESKeySpec(desKey);
            cipher.init(mode, keyFactory.generateSecret(desKeySpec), Holder.SECURE_RANDOM);
            return cipher.doFinal(data);
        } catch (Exception var6) {
            throw Exceptions.unchecked(var6);
        }
    }
}

python

import base64
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad


def encrypt_to_base64(plain_text: bytes, des_key) -> str:
    cipher = DES.new(des_key, DES.MODE_ECB)
    encrypted_pad = cipher.encrypt(pad(plain_text, DES.block_size))
    return base64.b64encode(encrypted_pad).decode('utf-8')


def encrypt_to_hex(plain_text: bytes, des_key) -> str:
    cipher = DES.new(des_key, DES.MODE_ECB)
    encrypted_pad = cipher.encrypt(pad(plain_text, DES.block_size))
    return encode_bytes(encrypted_pad)


def decrypt_from_base64(encrypted: str, des_key: bytes) -> str:
    encrypted = base64.b64decode(encrypted)
    cipher = DES.new(des_key, DES.MODE_ECB)
    decrypted_pad = unpad(cipher.decrypt(encrypted), DES.block_size)
    return decrypted_pad.decode('utf-8')


def decrypt_from_hex(encrypted: str, des_key: bytes) -> str:
    encrypted = decode_bytes(encrypted)
    cipher = DES.new(des_key, DES.MODE_ECB)
    decrypted_pad = unpad(cipher.decrypt(encrypted), DES.block_size)
    return decrypted_pad.decode('utf-8')


def encode_bytes(byte_array: bytes) -> str:
    hex_string = ""
    hex_digits = "0123456789abcdef"
    for byte in byte_array:
        hex_string += hex_digits[byte // 16] + hex_digits[byte % 16]

    return hex_string


def decode_bytes(hex_string: str) -> bytes:
    hex_string = hex_string.strip().replace(" ", "")
    if len(hex_string) % 2 != 0:
        raise ValueError("Invalid hex string length")
    hex_digits = "0123456789abcdef"
    bytes_digits = bytearray()
    i = 0
    while i < len(hex_string):
        c1 = hex_string[i]
        c2 = hex_string[i + 1]
        if c1 not in hex_digits or c2 not in hex_digits:
            raise ValueError("Invalid hex string format")
        b = int(c1 + c2, 16)
        bytes_digits.append(b)
        i += 2
    return bytes(bytes_digits)


if __name__ == '__main__':
    data = "Hello, World!"
    key = b"02f9f24427473e7a7d2e7454660a283b"[:8]

    encrypted_data = "ad45bae20f6750e1a3433ff10a35f97a"
    print("加密后的数据:", encrypted_data)

    decrypted_data = decrypt_from_hex(encrypted_data, key)
    print("解密后的数据:", decrypted_data)

    encrypted_data = encrypt_to_hex(data.encode('utf-8'), key)
    print("加密后的数据:", encrypted_data)

标签:3DES,java,String,python,encrypted,hex,return,byte,data
From: https://www.cnblogs.com/guanchaoguo/p/17720620.html

相关文章

  • java循环
    publicclassTestWhile1{publicstaticvoidmain(String[]args){/*intnum=1;//条件初始化intresult=1;while(num<=13){//条件判断result*=num;//循环体num+=2;//num++//迭代}System.out.println(result);*//*intnu......
  • java抽象类和抽象方法
    1.抽象的概念 2.抽象类和抽象方法的使用1//抽象方法和抽象类的格式:2/*抽象方法:就是加上abstract关键字,然后去掉大括号,直接分号结束;3抽象类:抽象方法所在的类,必须是抽象类才行,在class之前的写上abstract即可。45如何使用抽象类和抽象方法61.不能直接创建(new)抽象类对......
  • java开发之个人微信的二次开发
    简要描述:设置个人头像请求URL:http://域名地址/sendHeadImage请求方式:POST请求头Headers:Content-Type:application/jsonAuthorization:Authorization值(登录获取码信息接口中返回的认证信息值)参数:参数名必选类型说明wId是string登录实例标识path是string图片url链接返回数据:参数名类型......
  • org/springframework/boot/maven/RepackageMojo has been compiled by a more recent
    项目场景:项目中执行clean,再执行install时报错,错误如下org/springframework/boot/maven/RepackageMojohasbeencompiledbyamorerecentversionoftheJavaRuntime(classfileversion61.0),thisversionoftheJavaRuntimeonlyrecognizesclassfileversionsupt......
  • 转~~Python:ModuleNotFoundError: No module named 模块名 错误及解决方案
    IDE中语法检查,运行都正常,Linux命令行远程运行就报错:参考文档:https://blog.csdn.net/SeaSky_Steven/article/details/106426985 1print(os.pardir)2sys.path.append(os.pardir)34'''5os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口;6sys模块负责程......
  • java日期时间类现在(java8及以后版本)推荐使用java.time 包中的类
    以下信息由AI模型"文心一言"提供,仅供参考:在Java8之后,推荐使用新的日期和时间API,即java.time包中的类。主要有以下原因:更好的设计和功能:新的日期和时间API在设计和功能上都更优。它包括时间、日期、时间间隔等更全面的表示,并支持更准确的计算和格式化。更全面的时间......
  • JavaScript实现数组对象去重
    有多种实现方式:一、使用 Set 对象:1Array.from(new Set(array))该方法会先创建一个 Set 对象,然后再使用 Array.from 方法将 Set 对象转换为数组,因为 Set 对象不允许有重复的元素,所以这样可以实现去重的效果。但是,如果数组中的元素是对象,Set 对......
  • java定时器
    好多朋友用过Windows的任务计划,也有不少程序迷自己曾写过时钟报警、系统自动关机等趣味程序,可却很少有朋友在Web工程中实现过类似功能。  有人说Timer只能规定从现在开始的多长时间后,每隔多久做一次事或在什么时间做一次事,那我想在每月1号或每天12点做一项工作如何做呢?你只要......
  • HBase(扫描HBase表的数据转化为对应的类Java代码)
    Msg实体类packagecom.xxxx.test01;publicclassMsg{privateStringname;privateStringbumen;privateStringaddress;privateStringdiyu;privateStringwangzhi;privateStringemail;privateStringdaibiao;privateStr......
  • MySQL数据库查询对象空值判断与Java代码示例【含面试题】
    AI绘画关于SD,MJ,GPT,SDXL百科全书面试题分享点我直达2023Python面试题2023最新面试合集链接2023大厂面试题PDF面试题PDF版本java、python面试题项目实战:AI文本OCR识别最佳实践AIGamma一键生成PPT工具直达链接玩转cloudStudio在线编码神器玩转GPUAI绘画、AI讲话、......