简体   繁体   中英

Android/PHP - Encryption and Decryption

I'm struggeling with code from this page: http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php

I want to send data from a server to an Android application and vice versa, but it should be sent as an encrypted string. However, I manage to encrypt and decrypt the string in PHP. But on Android the application crashes with the following error message when decrypting: java.lang.Exception: [decrypt] unable to parse ' as integer.

This error occours here in the for-loop:

    public static byte[] hexToBytes(String str) {
        if (str==null) {
                return null;
        } else if (str.length() < 2) {
                return null;
        } else {
                int len = str.length() / 2;
                byte[] buffer = new byte[len];

                for (int i=0; i<len; i++) {
                        buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                }
                System.out.println("Buffer: " + buffer);
                return buffer;
        }
}

This is by the way the string that should be decrypted: f46d86e65fe31ed46920b20255dd8ea6

You're talking about encrypting and decrypting, but you're showing code which simply turns numeric bytes (such as 0x4F ) into strings (such as "4F" ) -- which may be relevant to your transfer of data (if you cannot transfer binary format), but completely unrelated to encryption/decryption.

Since the Android code you have contains only a single Integer parse, have you examined the input you're giving it? str.substring(i*2,i*2+2) apparently contains data other than [0-9A-F] when the exception occurs. You should start by examining the string you've received and comparing it to what you sent, to make sure they agree and they only contain hexadecimal characters.

Edit -- passing the string "f46d86e65fe31ed46920b20255dd8ea6" through your hexToBytes() function works flawlessly. Your input is probably not what you think it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM