DES加密

package com.yinhoo.ca.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 对对象进行DES加密和解密,注意密钥长度都必须是8的倍数
 * 
 * @author ming.chen
 * @date 2011-2-15
 * @version $Revision$
 */
public class DESUtils {
    private static Logger logger = LoggerFactory.getLogger(DESUtils.class);

    public static byte[] encrypt(Object object, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            return cipher.doFinal(toByteArray(object));
        }
        catch (Throwable e) {
            logger.error("加密公钥过程中出错", e);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> T decrypt(byte[] src, String password) throws Exception {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        return (T) toObject(cipher.doFinal(src));
    }

    /**
     * 对象转数组,对象必须序列化
     * 
     * @param obj
     * @return
     */
    public static byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        }
        catch (IOException ex) {
            logger.error("将公钥对象转为字节数组过程中出错", ex);
        }
        return bytes;
    }

    /**
     * 数组转对象,对象必须序列化
     * 
     * @param bytes
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        }
        catch (IOException ex) {
            logger.error("将字节数组转为公钥对象过程中出错", ex);
        }
        catch (ClassNotFoundException ex) {
            logger.error("将字节数组转为公钥对象过程中出错", ex);
        }
        return (T) obj;
    }

    public static void main(String[] args) {
        // 待加密内容
        String str = "测试内容";
        // 密码,长度要是8的倍数
        String password = "12345678";
        byte[] result = encrypt(str, password);
        System.out.println("加密后内容为:" + new String(result));

        // 直接将如上内容解密
        try {
            String decryResult = (String) decrypt(result, password);
            System.out.println("加密后内容为:" + decryResult);
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }

    }
}

 

你可能感兴趣的:(java,Security)