简体   繁体   English

Android / PHP-加密和解密

[英]Android/PHP - Encryption and Decryption

I'm struggeling with code from this page: http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php 我正在为此页面上的代码苦苦挣扎: 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. 我想将数据从服务器发送到Android应用程序,反之亦然,但应将其作为加密字符串发送。 However, I manage to encrypt and decrypt the string in PHP. 但是,我设法用PHP加密和解密字符串。 But on Android the application crashes with the following error message when decrypting: java.lang.Exception: [decrypt] unable to parse ' as integer. 但是在Android上,解密时应用程序崩溃,并显示以下错误消息:java.lang.Exception:[decrypt]无法将'解析为整数。

This error occours here in the for-loop: 此错误在for循环中发生:

    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 这是应该解密的字符串: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. 您正在谈论加密和解密,但是您正在显示的代码只是将数字字节(例如0x4F )转换为字符串(例如"4F" )-这可能与数据传输有关(如果无法传输二进制格式),但与加密/解密完全无关。

Since the Android code you have contains only a single Integer parse, have you examined the input you're giving it? 由于您拥有的Android代码仅包含一个Integer解析,因此您是否检查了输入的内容? str.substring(i*2,i*2+2) apparently contains data other than [0-9A-F] when the exception occurs. 发生异常时str.substring(i*2,i*2+2)显然包含[0-9A-F]以外的数据。 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. 编辑-通过hexToBytes()函数传递字符串“ f46d86e65fe31ed46920b20255dd8ea6”可以正常工作。 Your input is probably not what you think it is. 您的输入可能与您想像的不一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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