PHP base64 编码不会被 Android 解码



我有一个PHP脚本,创建一个QR码的用户名和时间戳。我需要证明QR码来自我的服务器,所以我用私人RSA密钥加密用户名和时间戳。为了让它进入QR码,我然后用base64编码。

我首先在Android上试用它。我可以从QR码中获得字符串但当我在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
Android代码:

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 base64编码使用'+'符号。当它被放入QR码时,"+"作为空格出现。将' '替换为'+',可以很好地解码。

最新更新