Android实现DES和3DES算法

qizongshuai 2017-01-17

本文实现的Android下的是DES和3DES算法,Java同样也适用。

DES算法如下:

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

public class DESUtils {
 private static byte[] parse(String str) {
  byte[] b = new byte[str.length() / 2];
  for (int i = 0, n = str.length(); i < n; i += 2) {
   b[i / 2] = (byte) (Integer.parseInt(str.substring(i, i + 2), 16));
  }
  return b;
 }

 /**
  * 加密
  * @param src
  * @param password
  * @return
  */
 public static byte[] enCode(byte[] src, String password) {
  try {
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
   SecretKey key = keyFactory.generateSecret(new DESKeySpec(parse(password)));// 密钥
   Cipher cipher = Cipher.getInstance("DES");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   return cipher.doFinal(src);// 明文
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;

 }

 /**
  * 解密
  * @param src
  * @param password
  * @return
  * @throws Exception
  */
 public static byte[] deCode(byte[] src, String password) throws Exception {
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey key = keyFactory.generateSecret(new DESKeySpec(parse(password)));// 密钥
  Cipher cipher = Cipher.getInstance("DES");
  cipher.init(Cipher.DECRYPT_MODE, key);
  return cipher.doFinal(src);// 密文
 }
}

3DES算法是进行了3次DES算法。
E是代表加密,D代表解密,K1,K2,K3代表3个密钥。加密解密都是用DES算法,一般来说密钥需要3个或两个密钥,如果3个密钥都相同,则变成了DES算法,如果对加密强度要求没有那么高,可以用两个密钥,对应的是K1和K3密钥相同。
3DES加密过程:EK1(加密)-->DK2(解密)-->EK3(加密)
3DES解密过程:DK3(解密)-->EK2(加密)-->DK1(解密)

3DES算法如下:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class DES3Utils {

private static final String Algorithm = "DESede"; //定义 加密算法,可用 DES,DESede,Blowfish
   
    //keybyte为加密密钥,长度为24字节
    //src为被加密的数据缓冲区(源)
    public static byte[] encryptMode(byte[] keybyte, byte[] src) {
      try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);

            //加密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    //keybyte为加密密钥,长度为24字节
    //src为加密后的缓冲区
    public static byte[] decryptMode(byte[] keybyte, byte[] src) {     
    try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);

            //解密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    //转换成十六进制字符串
    public static String byte2hex(byte[] b) {
        String hs="";
        String stmp="";

        for (int n=0;n<b.length;n++) {
            stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length()==1) hs=hs+"0"+stmp;
            else hs=hs+stmp;
            if (n<b.length-1)  hs=hs+":";
        }
        return hs.toUpperCase();
    }
}

调用

//DES
 //DES加密
 byte[] en = DESUtils.enCode(hexStringToBytes("3132333435363738"), "A1A2A3A4A5A6A7A8");
 //DES解密 
 try {
  byte[] dn = DESUtils.deCode(hexStringToBytes("B1C3D2A87DBDB68FA73FBBBCD6F083AC"), "A1A2A3A4A5A6A7A8");
   
 } catch (Exception e) {
  e.printStackTrace();
 }
 
//3DES
 //3DES加密
 String key =  "A1A2A3A4A5A6A7A8" //K1密钥
   +"B1B2B3B4B5B6B7B8" //K2密钥
   +"A1A2A3A4A5A6A7A8"; //K3密钥
 byte[] result = DES3Utils.encryptMode(hexStringToBytes(key), hexStringToBytes("3132333435363738"));

 //3DES解密
 byte[] dnresult = DES3Utils.decryptMode(hexStringToBytes(key), hexStringToBytes("B0920ED6520EAF752E22A1F49B243353"));

//***************************************************************************************
 //实现String到byte的转换
 public static byte[] hexStringToBytes(String string) {
        String hexString = string.replaceAll(" ", "").toUpperCase();


        if (hexString.length() <= 0)
            return null;


        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    } 

DES的明文是3132333435363738,密钥是A1A2A3A4A5A6A7A8,加密后得到B1C3D2A87DBDB68FA73FBBBCD6F083AC,这里面前面16位是明文加密而来的,后面的A73FBBBCD6F083AC是由0808080808080808加密而来的。这8个08是算法自动填充上去的。3DES同样会填充8个08上去再加密。B0920ED6520EAF752E22A1F49B243353后面的2E22A1F49B243353是由填充的0808080808080808加密而来。

相关推荐