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

java 加解密工具类

程序员文章站 2024-03-14 14:25:28
...

 

import com.seeyon.ctp.util.UUIDLong;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Calendar;

public class DesUtil  {
    /**
     * encrypt(des加密,key为任意值做MD5加密)
     * @param key
     * @param text
     * @return
     * @throws Exception
     */
    public static String encrypt(String key,String text) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("md5");
        SecureRandom random = new SecureRandom();
        DESKeySpec keySpec = new DESKeySpec(md5.digest(key.getBytes("utf-8")));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("des");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("des");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
        byte[] cipherData = cipher.doFinal(text.getBytes());
        return new BASE64Encoder().encode(cipherData);
    }

    /**
     * encrypt(des解密,key为任意值做MD5加密)
     * @param key
     * @param text
     * @return
     * @throws Exception
     */
    public static String decrypt(String key,String text) throws Exception {
        byte[] cipherData =  new BASE64Decoder().decodeBuffer(text);
        MessageDigest md5 = MessageDigest.getInstance("md5");
        SecureRandom random = new SecureRandom();
        DESKeySpec keySpec = new DESKeySpec(md5.digest(key.getBytes("utf-8")));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("des");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("des");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, random);
        byte[] plainData = cipher.doFinal(cipherData);
        return new String(plainData,"Utf-8");
    }

   
}