Android:DES加密
private static final String KEY = "xxxxxx"; // KEY的字节长度必须超过24 public DESUtil(){ super(); } /** DES加密 * @param str 要加密的内容 */ public String getDES(String str){ if(TextUtils.isEmpty(str)){ return null; } try { byte[] data = str.getBytes("UTF-8"); byte[] key = KEY.getBytes(); LogUtil.info("json", "length= " + key.length); return Base64.encodeToString(des3EncodeECB(key,data), Base64.DEFAULT); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } /** * ECB加密,不要IV * @param key 密钥 * @param data 明文 * @return Base64编码的密文 * @throws Exception */ private byte[] des3EncodeECB(byte[] key, byte[] data) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, deskey); byte[] bOut = cipher.doFinal(data); return bOut; } /** * ECB解密,不要IV * @param key 密钥 * @param data Base64编码的密文 * @return 明文 * @throws Exception */ private byte[] ees3DecodeECB(byte[] key, byte[] data) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, deskey); byte[] bOut = cipher.doFinal(data); return bOut; } /** * CBC加密 * @param key 密钥 * @param keyiv IV * @param data 明文 * @return Base64编码的密文 * @throws Exception */ private byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(keyiv); cipher.init(Cipher.ENCRYPT_MODE, deskey, ips); byte[] bOut = cipher.doFinal(data); return bOut; } /** * CBC解密 * @param key 密钥 * @param keyiv IV * @param data Base64编码的密文 * @return 明文 * @throws Exception */ private byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(keyiv); cipher.init(Cipher.DECRYPT_MODE, deskey, ips); byte[] bOut = cipher.doFinal(data); return bOut; }