加密原理
DES 使用一个 56 位的
密钥以及附加的 8 位
奇偶校验位,产生最大 64 位的分组大小。这是一个
迭代的
分组密码,使用称为 Feistel 的技术,其中将加密的文本块分成两半。使用子密钥对其中一半应用循环功能,然后将输出与另一半进行“
异或”运算;接着交换这两半,这一过程会继续下去,但最后一个循环不交换。DES 使用 16 个循环,使用异或,置换,代换,移位操作四种基本运算。
/** * 使用DES算法完成对称加密 * * @param content 加密字符串 * @param key 密钥 * @param type 加密还是解密 * @return */ public static String des(String content, String key, int type) throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException { String charset = "utf-8"; byte[] keybytes = key.getBytes(charset); byte[] temp = new byte[8];//只取八位 //将一个数组拷贝到另一个数组 System.arraycopy(keybytes, 0, temp, 0, Math.min(temp.length, keybytes.length)); //获取密钥对象KeySpec为key子类 Key keySpec = new SecretKeySpec(temp, "des"); //获取密码生成器 Cipher cipher = Cipher.getInstance("des"); try { if (type == ENCODE) { //加密 //初始化密码生成器 cipher.init(Cipher.ENCRYPT_MODE, keySpec); //加密 byte[] bytes = cipher.doFinal(content.getBytes(charset)); return Base64.encodeToString(bytes, Base64.DEFAULT); }else if (type == DECODE){ //解密 //初始化密码生成器 cipher.init(Cipher.DECRYPT_MODE, keySpec); //把需要解密的字符串转换 因为之前是base64编码 byte[] decode = Base64.decode(content.getBytes(charset), Base64.DEFAULT); //解密 byte[] bytes = cipher.doFinal(decode); return new String(bytes,0,bytes.length); } } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return null; }
desede加密写法一样
只是 获取密钥方式
String charset = "UTF-8"; try { byte[] keyBytes = key.getBytes(charset); byte[] temp = new byte[24]; System.arraycopy(keyBytes, 0, temp, 0, Math.min(temp.length, keyBytes.length)); //获取密钥对象 Key keySpec = new SecretKeySpec(temp, "desede"); //获取密码生成器 Cipher cipher = Cipher.getInstance("desede");
aes
String charset = "UTF-8"; try { byte[] keyBytes = key.getBytes(charset); byte[] temp = new byte[32]; System.arraycopy(keyBytes, 0, temp, 0, Math.min(temp.length, keyBytes.length)); //获取密钥对象 Key keySpec = new SecretKeySpec(temp, "aes"); //获取密码生成器 Cipher cipher = Cipher.getInstance("aes");