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

DES对称加密实现_JAVA

程序员文章站 2024-03-14 14:21:04
...

 

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

/**
 * description:
 */

public class DESCUtils {
    private static final String key = "DES";

    /**
     * @param data
     * @param password
     * @param encryptOrDecryptMode Cipher.ENCRYPT_MODE   Cipher.DECRYPT_MODE
     * @return
     * @throws Exception
     */
    public static byte[] encryptOrDecrypt(byte[] data, String password, int encryptOrDecryptMode) throws Exception {
        SecureRandom secureRandom = new SecureRandom();
        DESKeySpec desKeySpec = new DESKeySpec(password.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(key);  //**工厂
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);  //生成**
        Cipher cipher = Cipher.getInstance(key);
        cipher.init(encryptOrDecryptMode, secretKey, secureRandom);
        return cipher.doFinal(data);
    }

    public static String encode(String data, String password) throws Exception {
        return Base64.encodeBase64String(encryptOrDecrypt(data.getBytes("UTF-8"), password, Cipher.ENCRYPT_MODE));
    }

    public static String decode(String data, String password) throws Exception {
        return new String(encryptOrDecrypt(Base64.decodeBase64(data), password, Cipher.DECRYPT_MODE), "UTF-8");
    }

    public static void main(String[] args) {
        String password = "hjkg&t*jf/";
        Map<String, Object> map = new HashMap<>();
        map.put("user", "jack");
        String s = JSONObject.toJSONString(map);
        System.out.println(s);
        try {
            String encode = encode(s, password);
            System.out.println("encode: " + encode);
            String decode = decode(encode, password);
            System.out.println("decode: " + decode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

运行结果:

{"user":"jack"}
encode: CBEUKiVQKk0fiV7EWEsfVQ==
decode: {"user":"jack"}

相关标签: 算法 java