我有一个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;
答案 0 :(得分:1)
PHP base64编码使用'+'符号。当这被放入QR码时,'+'作为空格出现。用'+'替换'',它被解码得很好。