携程 3DES加密解密 java python

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)

posted @ 2023-09-21 18:01  vx_guanchaoguo0  阅读(51)  评论(0编辑  收藏  举报