数据加密——对称加密

废话不多说,上需求上代码:

需求:

用对称加密将报文加密加压,解压解密。

import java.io.UnsupportedEncodingException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 提供加密算法,可以对输入的字符串进行加密、解密操作
 */
public class EncryptData {
    byte[] encryptKey;
    DESedeKeySpec spec;
    DESKeySpec dks;
    SecretKeyFactory keyFactory;
    SecretKey theKey;
    Cipher cipher;
    IvParameterSpec IvParameters;
    private String algorithm;

    public EncryptData(String str, String key) {
        init(str, key);
    }

    public EncryptData(String str) {
        init(str, null);
    }

    private void init(String str, String key) {
        try {
            // 检测是否有 TripleDES 加密的供应程序
            // 如无,明确地安装SunJCE 供应程序
            try {
                Cipher.getInstance("DESede");// DES,DESede,Blowfish
            } catch (Exception e) {
                System.err.println("Installling SunJCE provider.");
                Provider sunjce = new com.sun.crypto.provider.SunJCE();
                Security.addProvider(sunjce);
            }
            // 创建一个密钥
            this.algorithm = str;
            encryptKey = ((key != null && !"".equals(key)) ? key : "This is a SIP DESede Key").getBytes();
            if ("3DES".equalsIgnoreCase(str)) {
                spec = new DESedeKeySpec(encryptKey);
                // 得到 DESSede keys
                keyFactory = SecretKeyFactory.getInstance("DESede");
                // 生成一个 DESede 密钥对象
                theKey = keyFactory.generateSecret(spec);
                // 创建一个 DESede 密码
                cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
                // 为 CBC 模式创建一个用于初始化的 vector 对象
                IvParameters = new IvParameterSpec(new byte[]{38, 29, 36, 78, 90, 87, 65, 83});
            } else if ("DES".equalsIgnoreCase(str)) {
                dks = new DESKeySpec(encryptKey);
                keyFactory = SecretKeyFactory.getInstance("DES");
                theKey = keyFactory.generateSecret(dks);
                cipher = Cipher.getInstance("DES");
            } else if ("AES".equalsIgnoreCase(str)) {
                byte[] aeskey = {31, 29, 32, 78, 90, 87, 65, 83, 35, 36, 78, 90, 87, 65, 83, 67};
                theKey = new SecretKeySpec(aeskey, "AES");
                cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                IvParameters = new IvParameterSpec(new byte[]{38, 29, 36, 78, 90, 87, 65, 83, 29, 36, 78, 90, 87, 65, 83, 84});
            }
        } catch (Exception exc) {
            // 记录加密或解密操作错误
            exc.printStackTrace();
        }
    }

    /**
     * 加密算法
     *
     * @param password 等待加密的数据
     * @return 加密以后的数据
     * @throws Exception
     */
    public byte[] encrypt(byte[] password) {
        byte[] encrypted_pwd = null;

        try {
            // 以加密模式初始化密钥
            if ("3DES".equals(this.algorithm)) {
                cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
            } else if ("DES".equals(this.algorithm)) {
                cipher.init(Cipher.ENCRYPT_MODE, theKey, new SecureRandom());
            } else {
                cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
            }
            // 加密前的数据
            byte[] plainttext = password;
            // 加密数据
            encrypted_pwd = cipher.doFinal(plainttext);
        } catch (Exception ex) {
            // 记录加密错误
            ex.printStackTrace();
        }
        return encrypted_pwd;
    }

    /**
     * 解密算法
     *
     * @param password 加过密的数据
     * @return 解密后结果
     */
    public byte[] decrypt(byte[] password) {
        byte[] decrypted_password = null;
        try {
            // 以解密模式初始化密钥
            if ("3DES".equals(this.algorithm)) {
                cipher.init(Cipher.DECRYPT_MODE, theKey, IvParameters);
            } else if ("DES".equals(this.algorithm)) {
                cipher.init(Cipher.DECRYPT_MODE, theKey, new SecureRandom());
            } else {
                cipher.init(Cipher.DECRYPT_MODE, theKey, IvParameters);
            }
            // 构造解密前的数据
            byte[] decryptedPassword = password;
            // 解密后数据
            byte[] decrypted_pwd = cipher.doFinal(decryptedPassword);
            // 得到结果
            decrypted_password = decrypted_pwd;
        } catch (Exception ex) {
            // 记录解密错误
            ex.printStackTrace();
        }
        return decrypted_password;
    }

    public static void main(String args[]) throws UnsupportedEncodingException {
        String Str1 = "加密内容XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        //要加密的数据,在加密前做一下trim()操作
        Str1 = Str1.trim();
        //定义加密算法和密码
        EncryptData ed = new EncryptData("DES", "password");
        //对数据加密
        byte des[] = ed.encrypt(Str1.getBytes());
        //对加密后的数据压缩
        String deszip = ZipUtil.zip(des);
        System.out.println("加密压缩后:" + deszip);
        //解压数据
        byte[] redes = ZipUtil.unzip(deszip);
        //对数据解密
        byte[] mw = ed.decrypt(redes);
        System.out.println("解压解密后:" + new String(mw));
    }
}

压缩解压工具类:


import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ZipUtil {

    // 压缩
    public static String zip(byte[] result) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            GZIPOutputStream gzipout = new GZIPOutputStream(baos);
            gzipout.write(result);
            gzipout.finish();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        byte[] enbytes = Base64.encodeBase64(baos.toByteArray());
        return new String(enbytes);
    }

    // 解压
    public static byte[] unzip(String data) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] debytes = Base64.decodeBase64(data.getBytes());
        GZIPInputStream is = null;
        try {
            is = new GZIPInputStream(new ByteArrayInputStream(debytes));
            baos = new ByteArrayOutputStream();
            int i = 0;
            try {
                while ((i = is.read()) != -1) {
                    baos.write(i);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            is.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        return baos.toByteArray();
    }
}

以上就是对称加密的内容,非对称加密的后期会上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值