解決Linux操作系統下AES解密失敗的問題

本文轉自:

http://blog.csdn.net/hbcui1984/article/details/5753083


現象描述:
windows上加解密正常,linux上加密正常,解密時發生如下異常

javax.crypto.BadPaddingException: Given final block not properly padded

       at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
       at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
       at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
       at javax.crypto.Cipher.doFinal(DashoA13*..)
       at chb.test.crypto.AESUtils.crypt(AESUtils.java:386)
       at chb.test.crypto.AESUtils.AesDecrypt(AESUtils.java:254)
       at chb.test.crypto.AESUtils.main(AESUtils.java:40) 

解決方法:
經過檢查之後,定位在生成KEY的方法上,如下:
  1. public static SecretKey getKey (String strKey) {  
  2.          try {           
  3.             KeyGenerator _generator = KeyGenerator.getInstance( "AES" );  
  4.             _generator.init(128new SecureRandom(strKey.getBytes()));  
  5.                 return _generator.generateKey();  
  6.         }  catch (Exception e) {  
  7.              throw new RuntimeException( " 初始化密鑰出現異常 " );  
  8.         }  
  9.       }   
修改到如下方式,問題解決:

  1. public static SecretKey getKey(String strKey) {  
  2.        try {           
  3.           KeyGenerator _generator = KeyGenerator.getInstance( "AES" );  
  4.            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );  
  5.           secureRandom.setSeed(strKey.getBytes());  
  6.           _generator.init(128,secureRandom);  
  7.               return _generator.generateKey();  
  8.       }  catch (Exception e) {  
  9.            throw new RuntimeException( " 初始化密鑰出現異常 " );  
  10.       }  
  11.     }   

原因分析

SecureRandom 實現完全隨操作系統本身的內部狀態,除非調用方在調用 getInstance 方法之後又調用了 setSeed 方法;該實現在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系統上則不同。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章