1. 简介
算法 | 秘钥长度 | 秘钥长度默认值 | 工作模式 | 填充形式 | 备注 |
---|---|---|---|---|---|
DES | 56 | 56 | ECB,CBC,PCBC,CTR,CTS,CFB,CFB8至CFB128,OFB,OFB8至OFB128 | NoPadding,PKCS5Padding,ISO101126Padding | java6实现 |
DES | 56 | 56 | ECB,CBC,PCBC,CTR,CTS,CFB,CFB8至CFB128,OFB,OFB8至OFB128 | NoPadding,PKCS5Padding,ISO101126Padding | java6实现 |
2. java实现
public static String encryptDES(String plaintext) throws Exception { // 初始化秘钥 和加密算法 秘钥必须大于8位 SecretKeySpec keySpec = new SecretKeySpec("12345678".getBytes(StandardCharsets.UTF_8),"DES"); // 失去Cipher的实例 Cipher des = Cipher.getInstance("DES/ECB/PKCS5Padding"); // 对Cipher 实例进行初始化, des.init(Cipher.ENCRYPT_MODE,keySpec); // update并不会每次都减少要加密的字符串的长度,并不牢靠。现实中的状态是 xiaojianbang +hengdi 解密发现只有banghengdi des.update("xiaojianbang".getBytes(StandardCharsets.UTF_8)); // 加密 由字符串 失去的byte[] byte[] res=des.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); // 将 byte[] 实例化为 ByteString 对象 ByteString bty= ByteString.of(res); // hex 编码 String str_hex= bty.hex(); // base64 编码 String str_base64 = bty.base64(); return str_hex + " || " + str_base64; }
解密:
public static String decryptDES(String cipherText) throws Exception { // 将加密后base64编码的字符串 解码,并还原成 byte[] byte[] cipherTextBytes = ByteString.decodeBase64(cipherText).toByteArray(); SecretKeySpec keySpec = new SecretKeySpec("12345678".getBytes(StandardCharsets.UTF_8),"DES"); Cipher des = Cipher.getInstance("DES/ECB/PKCS5Padding"); des.init(Cipher.DECRYPT_MODE,keySpec); byte[] res=des.doFinal(cipherTextBytes); return new String(res); }