java DES加解密及Wrong key size错误
如下的DES加密方法会报错:Wrong key size
public static String encryptDES(String source) throws Exception{ SecretKeySpec skeySpec = new SecretKeySpec(ckplayerkey.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(source.getBytes("utf8")); String data=Base64.encodeBase64String(encrypted); return data; }
一开始以为将AES加密方法中的关键字直接改为DES就是DES加密了,没想到报错 Wrong key size,因为前端是用cryptojs加密的,所以找到了一个答案:https://blog.csdn.net/king7950/article/details/70157463 根据该文章在java端加密成功~~
DES加密 关键代码如下:
/** * DES加密 */ public static String encodeDES(String datasource){ try{ SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(ckplayerkey.getBytes()); //创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); //Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); //用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); //现在,获取数据并加密 return Base64.encodeBase64String(cipher.doFinal(datasource.getBytes())); }catch(Throwable e){ e.printStackTrace(); return null; } }
DES解密代码(未测试)如下:
/** * DES解密 */ public String decodeDES(String src) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom random = new SecureRandom(); // 创建一个DESKeySpec对象 DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE)); // 创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 将DESKeySpec对象转换成SecretKey对象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正开始解密操作 return IOUtils.toString(cipher.doFinal(Base64.decodeBase64(src)),"UTF-8"); }