【问题标题】:PHP base64 encode doesn't get decoded by AndroidPHP base64 编码不会被 Android 解码
【发布时间】:2011-07-26 23:03:32
【问题描述】:

我有一个 PHP 脚本,它根据用户名和时间戳创建 QR 码。我需要证明 QR 码来自我的服务器,所以我使用 RSA 私钥加密用户名和时间戳。为了将其放入 QR 码中,我对其进行 base64 编码。

我首先在 Android 上试用它。我可以从二维码中获取字符串,但是当我在 Android 中对其进行 base64 解码时,它返回 null。调试后似乎是因为字符串中有两个空格。当解码器来检查非法字符是否可以被4整除时,它显然失败了。变得绝望我删除了空格,但随后它改变了长度,所以计算仍然没有成功。我可以更改“安全”字符的空格吗?还是特定的编码/解码对不兼容??

PHP 代码:

$data = base64_encode($username."`".$timestamp);
$fp = fopen("private.pem", "r");
$private_key = fread($fp, 8192);
fclose($fp);
openssl_private_encrypt($data, &$encrypted_data, $private_key);
$encrypted_data_64 = base64_encode($encrypted_data);
// create QR code

安卓代码:

String s = data.getStringExtra("SCAN_RESULT");
byte[] b = Base64.decode(s.toCharArray());
// b is null at this point

它出错的 Base64 代码:是

// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
    return new byte[0];

// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++)  // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
    if (IA[str.charAt(i)] < 0)
    sepCnt++;

// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
    return null;

【问题讨论】:

  • 假设您可以打开密钥,PHP 端看起来没问题,您检查过$encrypted_data_64 不是空字符串吗?虽然不知道如何修复 Andriod :)
  • 理论上它不应该有所不同,但是使用 String.getBytes() 或 Base64.decode(String, int) 呢?
  • 你能把代码贴在某个地方吗?我想知道这些额外的空间是从哪里来的......如果它们在代码中或者在解码过程中被插入......
  • 空格在 $encrypted_data_64 (不为空)中。今晚我回家时可以发布代码。有什么特别的代码吗?
  • 我的意思是张贴二维码图片。但是如果 PHP 变量中有空格,这听起来像是 PHP 中的东西。 “纯”base64 应该只是 base64 集,末尾有可能的 '=' 字符,以根据需要四舍五入长度。

标签: php android base64


【解决方案1】:

PHP base64 编码使用“+”符号。当它被放入二维码时,“+”作为空格出现。将 ' ' 替换为 '+' 并且解码正常。

【讨论】:

  • 您是否将其粘贴在 URL 中?这不是 QR 的东西,而是 HTTP/URL 的东西。在 Wikipedia 上查找 Base64,尤其是“base64url”。如果这看起来像/在 URL 中,最好先将 '+' 替换为 '-' ,并将 '/' 替换为 '_',然后再将其粘贴到 URL 中,然后从 URL 中取回它。
  • 不,这不是 URL,只是我的应用使用的数据。
  • 奇数。当然,原生 QR 编码不应该对数据进行任何更改,任何字符替换。
猜你喜欢
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多