以下的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端加密成功~~ 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解密代碼(未測試)以下:dom
/** * 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"); }