我有一个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码后,“ +”作为空格出现。用“ +”代替“”,它可以很好地解码。
关于php - Android无法解码PHP base64编码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6837650/