ApiTest.java 2.13 KB
package com.topdraw.dockingapi;

import com.topdraw.dockingapi.util.DecryptUtils;
import lombok.SneakyThrows;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

/**
 * @author wenxin
 * @version 1.0
 * @date 2024/5/23 下午4:40
 */
public class ApiTest {


    @Test
    public void testMain() throws Exception {
        // 添加BouncyCastle提供者
        Security.addProvider(new BouncyCastleProvider());
        // 密钥
        byte[] keyBytes = "wmsj2021".getBytes(StandardCharsets.UTF_8); // DES密钥长度为8字节
        // 需要加密的数据
        String text = "{\"phoneNum\":\"13627618074\"}";
        byte[] data = text.getBytes(StandardCharsets.UTF_8);
        // 创建密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "DES");
        // 创建Cipher实例
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
        // 初始化Cipher
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        // 执行加密
        byte[] encryptedData = cipher.doFinal(data);
        // 打印加密结果(通常加密后的数据进行Base64编码或者十六进制编码显示)
        System.out.println("Encrypted Data: " + bytesToHex(encryptedData));
    }

    // 将字节转换为十六进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    @SneakyThrows
    @Test
    public void testEncode(){
        String text = "{\"phoneNum\":\"13627618074\"}";
        System.out.println(DecryptUtils.encode("wmsj2021", text));
        String tt="U0ELEkckqqxwzutWXbySgJmGbWQovd9n7UZSWqYt5HpXOxOsQwTnrjGp7geAhD/Mp9Jy3okXkRtt0cuFDdlMjPDgsBK3SMu0";
        System.out.println(DecryptUtils.decode("wmsj2021", tt));
    }
}