When loading a public RSA key (generated in golang)
openssl_public_encrypt('data to encrypt', $ciphertext, $public_key, OPENSSL_PKCS1_PADDING);
this error is returned
openssl_public_encrypt(): key parameter is not a valid public key
But if I generate a new RSA key in PHP and use that instead it works. The public key from golang is verified with the private key and works
Generated in PHP
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu/XgP4yNs1VUT13oHwQe
ZP3+XUMo6VjJJNintmcoE/pm5Lq3oQZMdjLjAIO4kRfQroDbhe8ojAKR0vqnUpU+
yYJnMjxUbc84lG4ZzfMOgpm6aCO1WamwemnSKxzc86fJUZq7ju4+R6LfjYl7zuYH
Z70OqisA5xtUxJD2WWdADSA7XIsLU+ykie+WFKSVSEr0w7QX7EY4eGpVtTYH8ZTE
5QaQSk8mBhp/5TN4/0Vi/NhH/HcUt8put0vTiwmVN/cXN/2pAGChvhTyXWSsVlRg
ks9aFBCx3Q3+IzVzySqhsaV1sXlATq4UF2ThROEkULpQsmyZcPMHviPrqBV5odHN
AAviq01kczxaSZaEN1qJtATYNNb93EivYHCaZ2dIGmdUeUzJOcn+522xbgyDlW39
JLRX8xFD343CicZwdzNH9euS8pz4dFM6WdTWDCo0TPi0G9TuXUEcQyXWZg3aHKTS
dOoinA1Ah/pGW8oBx1WNRGdtV97cHC58QGtnkqeLJuLLP1WJx1N9vZyEHJhD64Gb
C2KoFRDYf8ZuVU5jTWalCABZ0X/cCwxG5Rx+20N+nDqKDcGvUoO+2sxlpkVYKm8F
XMlQJ8SbVeCEsnApG3zzsi166C9XIE5lgxdIAriM56aLOeQaOJeIWrSBxhil2679
HIXXX1TQwvSLOZhQ09/P4W8CAwEAAQ==
-----END PUBLIC KEY-----
Generated in go
-----BEGIN RSA PUBLIC KEY-----
MIICCgKCAgEAzFO40GMae/oh6SKp+4RZrZjJ63Imk5SpVpQEYFxlbGaeypFkIMgZ
ct9kt52muC/c/e2JpM7xl0dt7l1kyx3sWidUdEsz8yava8G/070R77hwYnp4ugB1
81FHdY/EsXCzPLSr3tWs9pTbmrYBWZxUFNbvP5lNw7QqUoDKHmpPXH6Rdpo4fSwY
iZXihs+T0WV7yEBMqSURJCmO+ADq8mj4WYQMefvWWgC3CyfU09Vh4xDgFgvDG5un
B2ghH4uxMppJmkZY5Xqe60/hcVScgfLQhvzVCugoDk4Y64jwWcVU9/EzbkA8yPRj
rgK69q0wqLITaE2FQ69o4S+FQab66ZKPF5P6u+w5OQ1/coNhnkcVlLU74wLEHAB+
auAKSSKFPGQwUEgGZYLY4QBibYO5nl2HXWUizI5+wJA5cOR6A7T6UjRvZ1xLYHwG
8ZMcmj+qL7M0l9TK6Jd8ZX6AUdCAlch7d2QtybNNZKF9lV7uOQYn/CBg5+2dXVkF
X7Uju6gQlOBIuJTLYQQfVXwS9BrFBMkZIGMl/aQ0ORPpaxtpg2fAltcGGG3Xz9+9
Sk6F+VE6Ke1S+4BwiOOagfNik+WA7qVsKeQS41bBNPKfyLYNhsZV7p3e1858YtoG
aJF0VMAoX27bF0dik53O1n5fE1uXKqVKYFl35Y9m+nd7j0drfacJezUCAwEAAQ==
-----END RSA PUBLIC KEY-----
Generate keys in PHP
class Asymmetric {
protected $private_key;
const KEY_BITS = 4096;
const DIGEST_ALGORITHM = 'SHA512';
const ENCRYPT_PADDING = OPENSSL_PKCS1_PADDING;
const SIGN_ALGORITHM = OPENSSL_ALGO_SHA512;
public function generate_keys(): array{
$resource = openssl_pkey_new([
'digest_alg' => self::DIGEST_ALGORITHM,
'private_key_bits' => self::KEY_BITS,
'private_key_type' => OPENSSL_KEYTYPE_RSA
]);
openssl_pkey_export($resource, $this->private_key);
return [
$this->private_key,
openssl_pkey_get_details($resource)['key']
];
}
}