欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java DES对称加密工具类(就这一篇就够了)

程序员文章站 2024-03-14 14:21:52
...
package org.collect.test.des;

import org.collect.test.rsa.Base64Tool;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.SecureRandom;

/**
 * Des对称加密
 */
public class DesUtil {

    private static final String algorithm = "DES";
    private static final String key = "asde34675";


    public static void main(String[] args) throws Exception {
        String string = "勇敢行sfsdf3择发生的方式[email protected]#¥%……&*():“《》?@#$%^&()<>?:";
        String ssss =  DesUtil.encrypt(string);
        System.out.println(ssss);

        String xxxx = DesUtil.decrypt(ssss);
        System.out.println(xxxx);
    }



    /**
     * 加密
     */
    public static String encrypt(String string) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
        byte[] bytes = cipher.doFinal(string.getBytes("utf-8"));
        return Base64Tool.byteToBase64(bytes);
    }


    /**
     * 解密
     */
    public static String decrypt(String ssss) throws Exception {
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
        byte[] bytes = cipher.doFinal(Base64Tool.base64ToByte(ssss));
        String xxxx = new String(bytes, "utf-8");
        return xxxx;
    }



    private static Cipher getCipher(int type) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(algorithm);
        // 用密匙初始化Cipher对象
        cipher.init(type, securekey, random);
        return cipher;
    }


}

相关标签: Java