DES 数据加密

来源:互联网 发布:淘宝网情侣手机 编辑:程序博客网 时间:2024/06/05 00:58

在开发的时候向服务发起请求的时候,有时候请求的结果需要加密。
本文简单介绍下DES的加密用法;

一,八位的密钥的加解密

    String plaintext = "我1234567890从";    String ciphertext = DES.encryptDES(plaintext, "89018D39");            Log.d("DES","明文:" + plaintext);            Log.d("DES","密钥:" + "89018D39");            Log.d("DES","密文:" + ciphertext);            Log.d("DES","解密后:" + DES.decryptDES(ciphertext, "89018D39"));

日志:

 D/DES: 明文:我1234567890从 D/DES: 密钥:89018D39 D/DES: 密文:Tpv9Fxx36WElIZN1QdCZpa3NGbzSpyNi D/DES: 解密后:我1234567890从

涉及的两个类:

Base64 类

import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;/** * Created by jimda on 2016/7/14. */public class Base64 {    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"            .toCharArray();    /**     * data[]进行编码     *     * @param data     * @return     */    public static String encode(byte[] data) {        int start = 0;        int len = data.length;        StringBuffer buf = new StringBuffer(data.length * 3 / 2);        int end = len - 3;        int i = start;        int n = 0;        while (i <= end) {            int d = ((((int) data[i]) & 0x0ff) << 16)                    | ((((int) data[i + 1]) & 0x0ff) << 8)                    | (((int) data[i + 2]) & 0x0ff);            buf.append(legalChars[(d >> 18) & 63]);            buf.append(legalChars[(d >> 12) & 63]);            buf.append(legalChars[(d >> 6) & 63]);            buf.append(legalChars[d & 63]);            i += 3;            if (n++ >= 14) {                n = 0;                buf.append(" ");            }        }        if (i == start + len - 2) {            int d = ((((int) data[i]) & 0x0ff) << 16)                    | ((((int) data[i + 1]) & 255) << 8);            buf.append(legalChars[(d >> 18) & 63]);            buf.append(legalChars[(d >> 12) & 63]);            buf.append(legalChars[(d >> 6) & 63]);            buf.append("=");        } else if (i == start + len - 1) {            int d = (((int) data[i]) & 0x0ff) << 16;            buf.append(legalChars[(d >> 18) & 63]);            buf.append(legalChars[(d >> 12) & 63]);            buf.append("==");        }        return buf.toString();    }    public static byte[] decode(String s) {        ByteArrayOutputStream bos = new ByteArrayOutputStream();        try {            decode(s, bos);        } catch (IOException e) {            throw new RuntimeException();        }        byte[] decodedBytes = bos.toByteArray();        try {            bos.close();            bos = null;        } catch (IOException ex) {            System.err.println("Error while decoding BASE64: " + ex.toString());        }        return decodedBytes;    }    private static void decode(String s, OutputStream os) throws IOException {        int i = 0;        int len = s.length();        while (true) {            while (i < len && s.charAt(i) <= ' ')                i++;            if (i == len)                break;            int tri = (decode(s.charAt(i)) << 18)                    + (decode(s.charAt(i + 1)) << 12)                    + (decode(s.charAt(i + 2)) << 6)                    + (decode(s.charAt(i + 3)));            os.write((tri >> 16) & 255);            if (s.charAt(i + 2) == '=')                break;            os.write((tri >> 8) & 255);            if (s.charAt(i + 3) == '=')                break;            os.write(tri & 255);            i += 4;        }    }    private static int decode(char c) {        if (c >= 'A' && c <= 'Z')            return ((int) c) - 65;        else if (c >= 'a' && c <= 'z')            return ((int) c) - 97 + 26;        else if (c >= '0' && c <= '9')            return ((int) c) - 48 + 26 + 26;        else            switch (c) {                case '+':                    return 62;                case '/':                    return 63;                case '=':                    return 0;                default:                    throw new RuntimeException("unexpected code: " + c);            }    }}

DES类

import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;/** * Created by jimda on 2016/7/14. */public class DES {    private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };    public static String encryptDES(String encryptString, String encryptKey)            throws Exception {        IvParameterSpec zeroIv = new IvParameterSpec(iv);        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());        return Base64.encode(encryptedData);    }    public static String decryptDES(String decryptString, String decryptKey)            throws Exception {        byte[] byteMi = Base64.decode(decryptString);        IvParameterSpec zeroIv = new IvParameterSpec(iv);        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);        byte decryptedData[] = cipher.doFinal(byteMi);        return new String(decryptedData);    }}

二,密钥大于8位的DES加解密

   String plaintext = "我1234567890从";   String ciphertext = Des2.encode("eb3e52920ffcd2b676cb17c3528e974a",plaintext);             Log.d("DES","密钥:" + "eb3e52920ffcd2b676cb17c3528e974a");             Log.d("DES","解密后:" + Des2.decodeValue( "eb3e52920ffcd2b676cb17c3528e974a", ciphertext));

Log

 密钥:eb3e52920ffcd2b676cb17c3528e974a 解密后:我1234567890从

涉及的类
Des2

import java.security.Key;import java.security.SecureRandom;import java.security.spec.AlgorithmParameterSpec;import javax.crypto.Cipher;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.IvParameterSpec;public class Des2{    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";    private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };    /**     * DES算法,加密     *     * @param data 待加密字符串     * @param key  加密私钥,长度不能够小于8位     * @return 加密后的字节数组,一般结合Base64编码使用     * @throws CryptException 异常     */    public static String encode(String key,String data) throws Exception    {        return encode(key, data.getBytes());    }    /**     * DES算法,加密     *     * @param data 待加密字符串     * @param key  加密私钥,长度不能够小于8位     * @return 加密后的字节数组,一般结合Base64编码使用     * @throws CryptException 异常     */    public static String encode(String key,byte[] data) throws Exception    {        try        {            DESKeySpec dks = new DESKeySpec(key.getBytes());            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");            //key的长度不能够小于8位字节            Key secretKey = keyFactory.generateSecret(dks);            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);        //    IvParameterSpec iv = new IvParameterSpec("********".getBytes());            IvParameterSpec zeroIv = new IvParameterSpec(iv);            AlgorithmParameterSpec paramSpec = zeroIv;            cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);            byte[] bytes = cipher.doFinal(data);            return Base64.encode(bytes);        } catch (Exception e)        {            throw new Exception(e);        }    }    /**     * DES算法,解密     *     * @param data 待解密字符串     * @param key  解密私钥,长度不能够小于8位     * @return 解密后的字节数组     * @throws Exception 异常     */    public static byte[] decode(String key,byte[] data) throws Exception    {        try        {            SecureRandom sr = new SecureRandom();            DESKeySpec dks = new DESKeySpec(key.getBytes());            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");            //key的长度不能够小于8位字节            Key secretKey = keyFactory.generateSecret(dks);            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);        //    IvParameterSpec iv = new IvParameterSpec("********".getBytes());            IvParameterSpec zeroIv = new IvParameterSpec(iv);            AlgorithmParameterSpec paramSpec = zeroIv;            cipher.init(Cipher.DECRYPT_MODE, secretKey,paramSpec);            return cipher.doFinal(data);        } catch (Exception e)        {//         e.printStackTrace();            throw new Exception(e);        }    }    /**     * 获取编码后的值     * @param key     * @param data     * @return     * @throws Exception     * @throws Exception     */    public static String decodeValue(String key,String data) throws Exception    {        byte[] datas;        String value = null;        datas = decode(key, Base64.decode(data));        value = new String(datas);        if (value.equals("")){            throw new Exception();        }        return value;    }}
0 0
原创粉丝点击