Java中使用DES对称加解密
DESDES(Data Encryption Standard),即数据加密算法。是IBM公司于1975年研究成功并公开发表的。DES算法的入口参数有三个:Key、Data、Mode。其中Key为8个字节共64位,是DES算法的工作密钥;Data也为8个字节64位,是要被加密或被解密的数据;Mode为DES的工作方式,有两种:加密或解密。
安卓端对请求Web服务器请求字符串进行加密加密公共方法:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112package com.sz.kcygl.common.DESUtil;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;import com.sun.org.apache.xml.internal.security.utils.Base64;public class DESUtil { public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding"; /** * 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("12345678".getBytes()); AlgorithmParameterSpec paramSpec = iv; 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("12345678".getBytes()); AlgorithmParameterSpec paramSpec = iv; 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; }}