Linux下运行java DES解密失败,报javax.crypto.BadPaddingException:Given final block not properly padded

参考:http://blog.csdn.net/rj042/article/details/8196125

单点登录:https://github.com/ebnew/ki4so

redis客户端操作:http://itoedr.blog.163.com/blog/static/120284297201361843854546

GC问题:http://ifeve.com/garbage-collection-increasing-the-throughput/

DES java源代码如下:

[java]  view plain copy
  1. import java.security.InvalidKeyException;  
  2. import java.security.NoSuchAlgorithmException;  
  3. import java.security.SecureRandom;  
  4. import java.security.spec.InvalidKeySpecException;  
  5.   
  6. import javax.crypto.BadPaddingException;  
  7. import javax.crypto.Cipher;  
  8. import javax.crypto.IllegalBlockSizeException;  
  9. import javax.crypto.KeyGenerator;  
  10. import javax.crypto.NoSuchPaddingException;  
  11. import javax.crypto.SecretKey;  
  12. import javax.crypto.SecretKeyFactory;  
  13. import javax.crypto.spec.DESKeySpec;  
  14.   
  15. public class DESEncryptTest {  
  16. private static final String DES_ALGORITHM = "DES";  
  17.           
  18.     /** 
  19.      * DES加密 
  20.      * @param plainData 
  21.      * @param secretKey 
  22.      * @return 
  23.      * @throws Exception 
  24.      */  
  25.     public String encryption(String plainData, String secretKey) throws Exception{  
  26.   
  27.         Cipher cipher = null;  
  28.         try {  
  29.             cipher = Cipher.getInstance(DES_ALGORITHM);  
  30.             cipher.init(Cipher.ENCRYPT_MODE, generateKey(secretKey));  
  31.               
  32.         } catch (NoSuchAlgorithmException e) {  
  33.             e.printStackTrace();  
  34.         } catch (NoSuchPaddingException e) {  
  35.             e.printStackTrace();  
  36.         }catch(InvalidKeyException e){  
  37.               
  38.         }  
  39.           
  40.         try {  
  41.             // 为了防止解密时报javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher异常,  
  42.             // 不能把加密后的字节数组直接转换成字符串  
  43.             byte[] buf = cipher.doFinal(plainData.getBytes());  
  44.               
  45.             return Base64Utils.encode(buf);  
  46.               
  47.         } catch (IllegalBlockSizeException e) {  
  48.             e.printStackTrace();  
  49.             throw new Exception("IllegalBlockSizeException", e);  
  50.         } catch (BadPaddingException e) {  
  51.             e.printStackTrace();  
  52.             throw new Exception("BadPaddingException", e);  
  53.         }  
  54.           
  55.     }  
  56.   
  57.     /** 
  58.      * DES解密 
  59.      * @param secretData 
  60.      * @param secretKey 
  61.      * @return 
  62.      * @throws Exception 
  63.      */  
  64.     public String decryption(String secretData, String secretKey) throws Exception{  
  65.           
  66.         Cipher cipher = null;  
  67.         try {  
  68.             cipher = Cipher.getInstance(DES_ALGORITHM);  
  69.             cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));  
  70.               
  71.         } catch (NoSuchAlgorithmException e) {  
  72.             e.printStackTrace();  
  73.             throw new Exception("NoSuchAlgorithmException", e);  
  74.         } catch (NoSuchPaddingException e) {  
  75.             e.printStackTrace();  
  76.             throw new Exception("NoSuchPaddingException", e);  
  77.         }catch(InvalidKeyException e){  
  78.             e.printStackTrace();  
  79.             throw new Exception("InvalidKeyException", e);  
  80.               
  81.         }  
  82.           
  83.         try {  
  84.               
  85.             byte[] buf = cipher.doFinal(Base64Utils.decode(secretData.toCharArray()));  
  86.               
  87.             return new String(buf);  
  88.               
  89.         } catch (IllegalBlockSizeException e) {  
  90.             e.printStackTrace();  
  91.             throw new Exception("IllegalBlockSizeException", e);  
  92.         } catch (BadPaddingException e) {  
  93.             e.printStackTrace();  
  94.             throw new Exception("BadPaddingException", e);  
  95.         }  
  96.     }  
  97.       
  98.       
  99.     /** 
  100.      * 获得秘密密钥 
  101.      *  
  102.      * @param secretKey 
  103.      * @return 
  104.      * @throws NoSuchAlgorithmException  
  105.      */  
  106.     private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{  
  107.         SecureRandom secureRandom = new SecureRandom(secretKey.getBytes());  
  108.                   
  109.         // 为我们选择的DES算法生成一个KeyGenerator对象  
  110.         KeyGenerator kg = null;  
  111.         try {  
  112.             kg = KeyGenerator.getInstance(DES_ALGORITHM);  
  113.         } catch (NoSuchAlgorithmException e) {  
  114.         }  
  115.         kg.init(secureRandom);  
  116.         //kg.init(56, secureRandom);  
  117.           
  118.         // 生成密钥  
  119.         return kg.generateKey();  
  120.     }  
  121.               
  122.     public static void main(String[] a) throws Exception{  
  123.         String input = "cy11Xlbrmzyh:604:301:1353064296";  
  124.         String key = "37d5aed075525d4fa0fe635231cba447";  
  125.           
  126.         DESEncryptTest des = new DESEncryptTest();  
  127.           
  128.         String result = des.encryption(input, key);  
  129.         System.out.println(result);  
  130.           
  131.         System.out.println(des.decryption(result, key));  
  132.               
  133.     }  
  134.           
  135.     static class Base64Utils {  
  136.   
  137.         static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();  
  138.         static private byte[] codes = new byte[256];  
  139.         static {  
  140.             for (int i = 0; i < 256; i++)  
  141.                 codes[i] = -1;  
  142.             for (int i = 'A'; i <= 'Z'; i++)  
  143.                 codes[i] = (byte) (i - 'A');  
  144.             for (int i = 'a'; i <= 'z'; i++)  
  145.                 codes[i] = (byte) (26 + i - 'a');  
  146.             for (int i = '0'; i <= '9'; i++)  
  147.                 codes[i] = (byte) (52 + i - '0');  
  148.             codes['+'] = 62;  
  149.             codes['/'] = 63;  
  150.         }  
  151.           
  152.         /** 
  153.          * 将原始数据编码为base64编码 
  154.          */  
  155.         static public String encode(byte[] data) {  
  156.             char[] out = new char[((data.length + 2) / 3) * 4];  
  157.             for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {  
  158.                 boolean quad = false;  
  159.                 boolean trip = false;  
  160.                 int val = (0xFF & (int) data[i]);  
  161.                 val <<= 8;  
  162.                 if ((i + 1) < data.length) {  
  163.                     val |= (0xFF & (int) data[i + 1]);  
  164.                     trip = true;  
  165.                 }  
  166.                 val <<= 8;  
  167.                 if ((i + 2) < data.length) {  
  168.                     val |= (0xFF & (int) data[i + 2]);  
  169.                     quad = true;  
  170.                 }  
  171.                 out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];  
  172.                 val >>= 6;  
  173.                 out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];  
  174.                 val >>= 6;  
  175.                 out[index + 1] = alphabet[val & 0x3F];  
  176.                 val >>= 6;  
  177.                 out[index + 0] = alphabet[val & 0x3F];  
  178.             }  
  179.               
  180.             return new String(out);  
  181.         }  
  182.   
  183.         /** 
  184.          * 将base64编码的数据解码成原始数据 
  185.          */  
  186.         static public byte[] decode(char[] data) {  
  187.             int len = ((data.length + 3) / 4) * 3;  
  188.             if (data.length > 0 && data[data.length - 1] == '=')  
  189.                 --len;  
  190.             if (data.length > 1 && data[data.length - 2] == '=')  
  191.                 --len;  
  192.             byte[] out = new byte[len];  
  193.             int shift = 0;  
  194.             int accum = 0;  
  195.             int index = 0;  
  196.             for (int ix = 0; ix < data.length; ix++) {  
  197.                 int value = codes[data[ix] & 0xFF];  
  198.                 if (value >= 0) {  
  199.                     accum <<= 6;  
  200.                     shift += 6;  
  201.                     accum |= value;  
  202.                     if (shift >= 8) {  
  203.                         shift -= 8;  
  204.                         out[index++] = (byte) ((accum >> shift) & 0xff);  
  205.                     }  
  206.                 }  
  207.             }  
  208.             if (index != out.length)  
  209.                 throw new Error("miscalculated data length!");  
  210.             return out;  
  211.         }  
  212.     }  
  213. }  


此代码在windows下运行正常,对加密后的密文可以正常解密。运行结果如下:

xl1nEww4mm09EvMy3tETBNg8HSfTFeBoilhNT7uBKBg=
cy11Xlbrmzyh:604:301:1353064296

但是放到linux上运行,则报错,错误信息如下图:

通过图片可以看到,对相同的明文(cy11Xlbrmzyh:604:301:1353064296)进行加密,在linux上加密后的结果和在windows上是不同的;而且在linux上不能对加密之后的密文进行解密,并抛出异常。

 

原因:
经过检查之后,定位在生成KEY的方法上,即如下红色代码:
[java]  view plain copy
  1. /** 
  2.      * 获得秘密密钥 
  3.      *  
  4.      * @param secretKey 
  5.      * @return 
  6.      * @throws NoSuchAlgorithmException  
  7.      */  
  8.     private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{  
  9.         <span style="color:#ff0000;">SecureRandom secureRandom = new SecureRandom(secretKey.getBytes()); //主要是此处代码  
  10. </span>               
  11.         // 为我们选择的DES算法生成一个KeyGenerator对象  
  12.         KeyGenerator kg = null;  
  13.         try {  
  14.             kg = KeyGenerator.getInstance(DES_ALGORITHM);  
  15.         } catch (NoSuchAlgorithmException e) {  
  16.         }  
  17.         kg.init(secureRandom);  
  18.         //kg.init(56, secureRandom);  
  19.           
  20.         // 生成密钥  
  21.         return kg.generateKey();  
  22.     }  

SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在 getInstance 方法,然后调用 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。关于SecureRandom类的详细介绍,见 http://yangzb.iteye.com/blog/325264

 

解决办法

 方法1:把原来的generateKey方法中红色如下的红色部分:

[java]  view plain copy
  1. /** 
  2.  * 获得秘密密钥 
  3.  *  
  4.  * @param secretKey 
  5.  * @return 
  6.  * @throws NoSuchAlgorithmException  
  7.  */  
  8. private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{  
  9.     <span style="color:#ff0000;"><span><code class="comments">//防止linux下 随机生成key</code></span>  
  10.     SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");  
  11.     secureRandom.setSeed(secretKey.getBytes());  
  12. /span>        
  13.     // 为我们选择的DES算法生成一个KeyGenerator对象  
  14.     KeyGenerator kg = null;  
  15.     try {  
  16.         kg = KeyGenerator.getInstance(DES_ALGORITHM);  
  17.     } catch (NoSuchAlgorithmException e) {  
  18.     }  
  19.     kg.init(secureRandom);  
  20.     //kg.init(56, secureRandom);  
  21.       
  22.     // 生成密钥  
  23.     return kg.generateKey();  
  24. }  


方法2:不使用SecureRandom生成SecretKey,而是使用SecretKeyFactory;重新实现方法generateKey,代码如下

[java]  view plain copy
  1. /** 
  2.  * 获得密钥 
  3.  *  
  4.  * @param secretKey 
  5.  * @return 
  6.  * @throws NoSuchAlgorithmException  
  7.  * @throws InvalidKeyException  
  8.  * @throws InvalidKeySpecException  
  9.  */  
  10. private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException,InvalidKeyException,InvalidKeySpecException{  
  11.       
  12.     SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);  
  13.     DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());  
  14.     keyFactory.generateSecret(keySpec);  
  15.     return keyFactory.generateSecret(keySpec);  
  16. }  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值