Java AES解密问题

我的任务是解密使用以下标准加密的Java文件:

AES加密算法,128位密钥,ECB模式和PKCS7填充。 加密文件格式为: – 第一个字节为hex0x31 – 指定使用的加密方法(AES为1) – 后跟输入文件的加密字节

我还必须下载文件,所以这是我到目前为止的尝试:

下载代码,我跳过这里的第一个字节,因为它不是必需的,也没有加密:


final String PATH = "/sdcard/" + IMEI + ".xml"; //put the downloaded file here try { URL url = new URL(context.getString(R.string.xml_feed) + IMEI + ".xml"); enc_File = new File(PATH); long startTime = System.currentTimeMillis(); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); /* * Define InputStreams to read from the URLConnection. */ InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); /* * Read bytes to the Buffer until there is nothing more to read(-1). */ ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; bis.skip(1); while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ FileOutputStream fos = new FileOutputStream(enc_File); fos.write(baf.toByteArray()); fos.close(); } catch (IOException e) { } } 

这给了我下载的加密文件,所以我尝试使用以下代码解密此文件:


  String bytes = toHex("the 16 bit key"); Key skeySpec = new SecretKeySpec(toByte(bytes), "AES"); Cipher c = Cipher.getInstance("AES/ECB/PKCS7Padding"); byte[] buf = new byte[1024]; // Bytes read from in will be decrypted InputStream inCipher = new FileInputStream(enc_File); OutputStream outCipher = new FileOutputStream(cipherFile); c.init(Cipher.DECRYPT_MODE, skeySpec); inCipher = new CipherInputStream(inCipher, c); // Read in the decrypted bytes and write the cleartext to out int numRead = 0; while ((numRead = inCipher.read(buf)) >= 0) { outCipher.write(buf, 0, numRead); } outCipher.close(); 

以上应该在新文件中给我解密的数据。

以下是该代码中使用的util方法,用于为SecretKeySpec创建密钥字节格式


 public static byte[] toByte(String hexString) { int len = hexString.length()/2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue(); return result; } public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2*buf.length); for (int i = 0; i >4)&0x0f)).append(HEX.charAt(b&0x0f)); } public static String toHex(String txt) { return toHex(txt.getBytes()); } public static String fromHex(String hex) { return new String(toByte(hex)); } 

然而,这目前给我以下例外:

 10-12 11:19:26.337: WARN/System.err(5376): java.io.IOException: last block incomplete in decryption 

加密文件下载正常,解密运行但我得到上述exception,并检查应该解密的文件显示文件的第一行正确解密,然后下一对行的小部分然后返回垃圾其余的。

我现在不知道在哪里找不到问题,有人可以帮忙吗? 或者指出我可能导致exception的方向?

附加信息:

 10-12 15:30:37.291: WARN/System.err(6898): at com.mypackage.net.SettingsProvisioner.getRoutingDoc(SettingsProvisioner.java:217) 

以上行来自log cat(stacktrace)中的exception

它表明在这行代码中发生了exception:

 while ((numRead = inCipher.read(buf)) >= 0) { 

没有完整的堆栈跟踪,很难调试我们必须重新编译你的代码,如果由于安全原因你不能在这里发布(显而易见)尝试像IBM stackanalyzer或lady4j这样的堆栈跟踪分析器

该分析仪适用于各种开发(包括Android)