Linux下AES解密失敗
阿新 • • 發佈:2019-02-14
invalid 部分 see byte blocks tst valid generator stack
在win下正常運行但在linux下報錯Given final block not properly padded. Such issues can arise if a bad key 好像是因為win中生成的key是一樣的,而在部分linux下會變成隨機
一下是解密修改前後的對照
1 public static byte[] decrypt(byte[] content) { 2 String password="123456"; 3 try { 4 KeyGenerator kgen = KeyGenerator.getInstance("AES");//創建AES的Key生產者 5 //防止linux下 隨機生成key 6 SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); 7 random.setSeed(password.getBytes("UTF-8")); 8 kgen.init(128, random); 9 //kgen.init(128, new SecureRandom(password.getBytes())); 10 SecretKey secretKey = kgen.generateKey();//根據用戶密碼,生成一個密鑰 11 byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰 12 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰 13 Cipher cipher = Cipher.getInstance("AES");// 創建密碼器 14 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化為解密模式的密碼器15 byte[] result = cipher.doFinal(content); 16 return result; // 明文 17 18 } catch (NoSuchAlgorithmException e) { 19 e.printStackTrace(); 20 } catch (NoSuchPaddingException e) { 21 e.printStackTrace(); 22 } catch (InvalidKeyException e) { 23 e.printStackTrace(); 24 } catch (IllegalBlockSizeException e) { 25 e.printStackTrace(); 26 } catch (BadPaddingException e) { 27 e.printStackTrace(); 28 } catch (UnsupportedEncodingException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 return null; 33 }
下面是修改過的
1 public static byte[] decrypt(byte[] content) { 2 String password="123456"; 3 try { 4 KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者 5 //防止linux下 隨機生成key 6 SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); 7 random.setSeed(password.getBytes("UTF-8")); 8 kgen.init(128, random); 9 //kgen.init(128, new SecureRandom(password.getBytes())); 10 SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰 11 byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰 12 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰 13 Cipher cipher = Cipher.getInstance("AES");// 創建密碼器 14 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化為解密模式的密碼器 15 byte[] result = cipher.doFinal(content); 16 return result; // 明文 17 18 } catch (NoSuchAlgorithmException e) { 19 e.printStackTrace(); 20 } catch (NoSuchPaddingException e) { 21 e.printStackTrace(); 22 } catch (InvalidKeyException e) { 23 e.printStackTrace(); 24 } catch (IllegalBlockSizeException e) { 25 e.printStackTrace(); 26 } catch (BadPaddingException e) { 27 e.printStackTrace(); 28 } catch (UnsupportedEncodingException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 return null; 33 }
Linux下AES解密失敗