Java AES解密问题

发布于 2024-09-26 23:36:42 字数 3940 浏览 1 评论 0原文

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

具有 128 位密钥、ECB 模式和 PKCS7 填充的 AES 加密算法。 加密后的文件格式为: - 第一个字节是十六进制 0x31 - 指定使用的加密方法(1 表示 AES) - 接下来是输入文件的加密字节

我还必须下载该文件,所以这是我迄今为止的尝试:

下载代码,我在这里跳过第一个字节,因为它不是必需的并且未加密:


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 < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b>>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

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

我现在陷入困境,不知道在哪里寻找问题,有人可以帮忙吗?或者指出可能导致异常的原因?

其他信息:

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

上面的行来自日志cat(stacktrace)中的异常

,它表明异常发生在这行代码中:

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

I have been tasked with decrypting a file in Java that has been encrypted using the following criteria:

AES encryption algorithm with 128-bit key, ECB mode and PKCS7 padding.
The encrypted file format is:
- first byte is hex 0x31 – specifying encryption method used (1 for AES)
- followed by the encrypted bytes of the input file

I must also download the file, so here is my attempt so far:

The download code, I skip the first byte here as it is not required and is not encrypted:


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) {

        }

    }

This gives me the encrypted file downloaded, So I then try to decrypt this file using the following code:


         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(); 

the above should give me the decryted data in a new file.

And here are the util methods used in that code to create the Key in Byte format for the 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 < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b>>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));
}

However this currently gives me the following exception:

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

The encrypted file downloads fine, the decrytption runs but I get the above exception and checking the file that should be decrypted reveals that the first line of the file decrypted properly and then small parts of the next couple of lines but then returns junk for the rest.

I'm stuck at this now not knowing where to look for the problem, can anybody help? Or point me in the direction of what may be causing the exception?

Additional info:

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

The above line is from the exception in the log cat (stacktrace)

And it shows that the exception is occuring at this line of code:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩人痒 2024-10-03 23:36:42

如果没有完整的堆栈跟踪,则很难进行调试,我们将不得不重新编译您的代码,如果您出于安全原因无法将其发布到此处(显然),请尝试使用堆栈跟踪分析器,例如 IBM stackanalyzer 或 lady4j

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

Without the full stacktrace it is dificult to debug we would have to recompile your code, if you can not post it here for security reasons (obvious) try a stacktrace analyzer like the IBM stackanalyzer or lady4j

The analyzer works for everykind of development (Android included)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文