Chinaunix首页 | 论坛 | 博客
  • 博客访问: 836830
  • 博文数量: 182
  • 博客积分: 1992
  • 博客等级: 上尉
  • 技术积分: 1766
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-18 11:49
文章分类

全部博文(182)

文章存档

2019年(1)

2016年(5)

2015年(29)

2014年(38)

2013年(21)

2012年(36)

2011年(52)

我的朋友

分类: Java

2014-09-22 15:01:35

Exception: Input length must be multiple of 8 when decrypting with padded cipher

点击(此处)折叠或打开

  1. public static String encryptToDES(String info) {
  2.         SecretKey key = createSecretKey("DES", KEY);
  3.         // 定义 加密算法,可用 DES,DESede,Blowfish
  4.         String Algorithm = "DES";
  5.         // 加密随机数生成器 (RNG),(可以不写)
  6.         //SecureRandom sr = new SecureRandom();
  7.         // 定义要生成的密文
  8.         byte[] cipherByte = null;
  9.         try {
  10.             // 得到加密/解密器
  11.             Cipher c1 = Cipher.getInstance(Algorithm);
  12.             // 用指定的密钥和模式初始化Cipher对象
  13.             // 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
  14.             c1.init(Cipher.ENCRYPT_MODE, key);
  15.             // 对要加密的内容进行编码处理,
  16.             cipherByte = c1.doFinal(info.getBytes());
  17.         } catch (Exception e) {
  18.             e.printStackTrace();
  19.         }
  20.         if (cipherByte == null) {
  21.             return "";
  22.         } else {
  23.             return byteArrayToString(cipherByte); //不能用new String(byte[]),这样会改变在decrypt时byte[]已经改变了,会报错误
  24.         }
  25.         
  26.     }
  27.     
  28.     public static String decryptByDES(String s) {
  29.         byte[] sInfo = stringToByteArray(s);
  30.         SecretKey key = createSecretKey("DES", KEY);
  31.         // 定义 加密算法,
  32.         String Algorithm = "DES";
  33.         // 加密随机数生成器 (RNG)
  34.         //SecureRandom sr = new SecureRandom();
  35.         byte[] cipherByte = null;
  36.         try {
  37.             // 得到加密/解密器
  38.             Cipher c1 = Cipher.getInstance(Algorithm);
  39.             // 用指定的密钥和模式初始化Cipher对象
  40.             c1.init(Cipher.DECRYPT_MODE, key);
  41.             // 对要解密的内容进行编码处理
  42.             cipherByte = c1.doFinal(sInfo);
  43.         } catch (Exception e) {
  44.             e.printStackTrace();
  45.         }
  46.         // return byte2hex(cipherByte);
  47.         //System.out.println(cipherByte);
  48.         if (cipherByte == null) {
  49.             return "";
  50.         } else {
  51.             return new String(cipherByte);
  52.         }
  53.     }
以上代码还是会出现问题,问题可能很难遇到,那就是在byteArrayToString方法中,一定要转好,不能直接把byte做一个char,如果这个char正好是"回车"那就麻烦了,我的做法是就把byte值存下来,并用:分隔,用时再转换成byte数组

点击(此处)折叠或打开

  1. for (int i = 0; i < barray.length; i++) {
  2.             s += barray[i];
  3.             if (i != barray.length - 1) {
  4.                 s += ":";
  5.             }
  6.         }




阅读(1031) | 评论(0) | 转发(0) |
0

上一篇:jarsigner签名apk

下一篇:android加载大图片

给主人留下些什么吧!~~