使用php獲取pubkey.bin以后,獲取到了二進(jìn)制文件,但是始終無法用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) {
// 解析錯(cuò)誤處理
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);
?>
// 讀取二進(jìn)制文件
$binaryData = file_get_contents('binaryfile.bin');
// 轉(zhuǎn)換二進(jìn)制數(shù)據(jù)為十六進(jìn)制
$hexData = bin2hex($binaryData);
// 將十六進(jìn)制數(shù)據(jù)轉(zhuǎn)換為 PEM 格式
$pemKey = "-----BEGIN PUBLIC KEY-----\n" .
chunk_split($hexData, 64, "\n") .
"-----END PUBLIC KEY-----\n";
// 獲取公鑰
$publicKey = openssl_pkey_get_public($pemKey);
gpt翻譯如下:
$text = "pub";
$text .= "@@@" . round(microtime(true) * 1000); // Equivalent of new Date().getTime() in Java
$fileContent = file_get_contents("pubkey.bin");
$key = openssl_get_publickey($fileContent);
$cipherText = '';
openssl_public_encrypt($text, $cipherText, $key, OPENSSL_PKCS1_PADDING);
$accessKey = base64_encode($cipherText);