使用php获取pubkey.bin以后,获取到了二进制文件,但是始终无法用X509加载
这是php代码
$file = 'pubkey.bin';
$handle = fopen($file, "rb");
if ($handle) {
$contents = fread($handle, filesize($file));
fclose($handle);
} else {
return "无法打开文件";
}
$string = base64_encode(serialize($contents));
$beginpem = "-----BEGIN CERTIFICATE-----\r\n";
$endpem = "-----END CERTIFICATE-----";
$string = $beginpem.$string.$endpem;
var_dump($string);
$certificate = openssl_x509_read($string);
if ($certificate === false) {
// 解析错误处理
return '无法解析';
}
return 'ok';
下面是java代码
String text = "pub";
text += "@@@" + new Date().getTime();
FileInputStream fis = new FileInputStream("pubkey.bin");
byte[] b = new byte[fis.available()];
fis.read(b);
fis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(b);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pubKey = factory.generatePublic(spec);
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.ENCRYPT_MODE, pubKey);
byte encryptOut[] = c.doFinal(text.getBytes());
String accessKey = new String(Base64.encodeBase64(encryptOut));
<?php
$text = "pub";
$text .= "@@@" . time();
$pubKey = file_get_contents('pubkey.bin');
$pubKey = openssl_pkey_get_public($pubKey);
$encryptOut = '';
openssl_public_encrypt($text, $encryptOut, $pubKey, OPENSSL_PKCS1_PADDING);
$accessKey = base64_encode($encryptOut);
?>
可能是因为这个bin文件的原因,读取出来后,使用openssl_pkey_get_public无法获取。。
gpt翻译如下: