des算法加密

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

/**
 *  DES加密解密模式:ecb
 *  填充:pkcs5padding
 *  密码:5SiKez2Y 输出格式HEX
 *  字符集Utf-8
 *  * @ClassName DesUtil
 *  * @Description
 *  * @createTime 2023/11/23
 * */
public class DesUtil {
    private static String PASSWORD  = "youPassword";
    private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";//算法/模式/补码方式
    public static final String ALGORITHM_NAME = "DES";
    public static String  encode(String data) throws Exception {
        SecretKeySpec key = new SecretKeySpec(PASSWORD.getBytes(StandardCharsets.UTF_8), ALGORITHM_NAME);
        // 加密
        Cipher cipherForEncryption = Cipher.getInstance(CIPHER_ALGORITHM);
        cipherForEncryption.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipherForEncryption.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encrypted); // 输出HEX格式
     }
    public static String decode(String data) throws Exception {
        // 将Base64编码的加密文本解码为字节数组
        byte[] encryptedBytes = hexStringToByteArray(data);
        SecretKeySpec key = new SecretKeySpec(PASSWORD.getBytes(StandardCharsets.UTF_8), ALGORITHM_NAME);
        // 创建解密器
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        // 将解密后的字节数组转换为UTF-8编码的字符串
        String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
        return decryptedText;
    }

    private static String bytesToHex(byte[] bytes) {
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
            return result.toString();
        }

    private static byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] byteArray = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
        byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i+1), 16));

        }
        return byteArray;
    }



    public static void main(String[] args) throws Exception {
        String str  = encode("{\"password\":\"9b2a6298a36606f3490ac0e0b8d9917d\",\"test\":\"3301063501\"}");
        System.out.println(str);
        System.out.println(decode(str));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值