I'm trying to use soap to call a webservice but I keep getting the following error "Warning: SoapClient::SoapClient(): Unable to set private key file".
I'm assuming that the error comes due to the fact the the .cer file I am using only includes public key and no private key. But i'm not sure of another way to use the .cer file. If i don't use the .cer file i can connect just fine and I am able to call and receive results when i use the __getFunctions() method. However, when i try to use other methods i need to be authorized and that leads to the problem. Below is the simple code i am trying to use. Please let me know if more information is required.
ini_set('display_errors',1);
error_reporting(E_ALL);
ini_set('soap.wsdl_cache_enabled', 0);
$username = 'user';
$password = 'pass';
$ns = 'GatewayEDI.WebServices';
$auth = array();
$auth['User'] = new SOAPVar($username, XSD_STRING, null, null, null, $ns);
$auth['Password'] = new SOAPVar($password, XSD_STRING, null, null, null, $ns);
$headerBody = new SOAPVar($auth, SOAP_ENC_OBJECT);
$header = new SOAPHeader($ns, 'AuthSOAPHeader', $headerBody);
$client=new SoapClient('https://url/Service.asmx?WSDL',
array(
'local_cert' => 'file.cer'
));
$client->__setSOAPHeaders(array($header));
$param = array(
'X12Input'=>"testing",
"GediPayerID"=>"52",
"ResponseDataType"=>"Xml"
);
//this leads to private key error
echo $result = $client->DoInquiryByX12Data($param,$header);
I believe your .pem/.cer file should have your private key in it:
-----BEGIN RSA PRIVATE KEY-----
# base64 encoded key
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
# base64 encoded cert
-----END CERTIFICATE-----
If your private key's first line has a directive similar to "Proc-Type: 4,ENCRYPTED" you'll need to include the "passphrase" option when constructing your SoapClient(). You can also strip the passphrase requirement with OpenSSL, my syntax is a bit rusty so you may want to double check if you try it:
openssl rsa -in /path/to/private.key -out /path/to/private.key
"private.key" should be just the private key in this context (you can add it into the .cer/.pem file after the passphrase has been removed.
Related
I am using firebase/php-jwt for generating JWT Token using the following PHP Source Code
<?php
include '../vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC8kGa1pSjbSYZVebtTRBLxBz5H4i2p/llLCrEeQhta5kaQu/Rn
vuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t0tyazyZ8JXw+KgXTxldMPEL9
5+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4ehde/zUxo6UvS7UrBQIDAQAB
AoGAb/MXV46XxCFRxNuB8LyAtmLDgi/xRnTAlMHjSACddwkyKem8//8eZtw9fzxz
bWZ/1/doQOuHBGYZU8aDzzj59FZ78dyzNFoF91hbvZKkg+6wGyd/LrGVEB+Xre0J
Nil0GReM2AHDNZUYRv+HYJPIOrB0CRczLQsgFJ8K6aAD6F0CQQDzbpjYdx10qgK1
cP59UHiHjPZYC0loEsk7s+hUmT3QHerAQJMZWC11Qrn2N+ybwwNblDKv+s5qgMQ5
5tNoQ9IfAkEAxkyffU6ythpg/H0Ixe1I2rd0GbF05biIzO/i77Det3n4YsJVlDck
ZkcvY3SK2iRIL4c9yY6hlIhs+K9wXTtGWwJBAO9Dskl48mO7woPR9uD22jDpNSwe
k90OMepTjzSvlhjbfuPN1IdhqvSJTDychRwn1kIJ7LQZgQ8fVz9OCFZ/6qMCQGOb
qaGwHmUK6xzpUbbacnYrIM6nLSkXgOAwv7XXCojvY614ILTK3iXiLBOxPu5Eu13k
eUz9sHyD6vkgZzjtxXECQAkp4Xerf5TGfQXGXhxIX52yH+N2LtujCdkQZjXAsGdm
B2zNzvrlgRmgBrklMTrMYgm1NPcW+bRLGcwgW2PTvNM=
-----END RSA PRIVATE KEY-----
EOD;
$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8kGa1pSjbSYZVebtTRBLxBz5H
4i2p/llLCrEeQhta5kaQu/RnvuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t
0tyazyZ8JXw+KgXTxldMPEL95+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4
ehde/zUxo6UvS7UrBQIDAQAB
-----END PUBLIC KEY-----
EOD;
$payload = [
'iss' => 'example.org',
'aud' => 'example.com',
'iat' => time(),
'nbf' => time() + 3600,
];
$jwt = JWT::encode($payload, $privateKey, 'RS256');
echo "Encode:\n" . print_r($jwt, true) . "<br/><br/>";
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
*/
$decoded_array = (array) $decoded;
echo "Decode:\n" . print_r($decoded_array, true) . "<br/>";
The code works fine, I am able to decode the Token properly, but when I try to verify the token using the Debugger on https://jwt.io/, it's giving an error saying, it's an invalid token.
Here is the JWT.io link with all the fields.
Note: I have read all the related questions and I am posting this question since they are unable to fix my issue.
Thanks in advance!!!
Screenshot:
Your key size is 1024 bit:
# key.pem is
# -----BEGIN RSA PRIVATE KEY-----
# MIICXAIBAAKBgQC8kGa1p...
# ...
openssl rsa -text -noout -in key.pem
RSA Private-Key: (1024 bit, 2 primes)
Now let's check for minimum requirements for RS256:
Required key size: At least 2048 bits
You have to create more secured key
I'm trying to convert key pair from PEM format :
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
Into XML format :
<RSAKeyValue>
<Exponent> </Exponent>
<Modulus> </Modulus>
</RSAKeyValue>
Is it possible using only openssl as I generate the keys through it ?
nb : my keys are stored into $privKey and $pubKey variable for test purpose, so I want to be able to $echo the XML format key and not store it into a file for the moment.
nb' : I have tried using phpseclib with an exemple found here but it gives me this error "Uncaught Error: Class "BaseController" not found in ..."
Thanks for your help
Here is the PHP code :
<?php
$config = array
(
'config' => 'C:\xampp\htdocs\crypto\openssl.cnf',
'default_md' => 'sha512',
'private_key_bits' => 4096,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
);
$keypair = openssl_pkey_new($config);
openssl_pkey_export($keypair, $privKey, null, $config);
$publickey = openssl_pkey_get_details($keypair);
$pubKey = $publickey['key'];
use phpseclib3\Crypt\RSA;
echo $pubKey->toString("XML");
echo "$privKey";
?>
The conversion of a PEM encoded key in X.509/SPKI format to XML format can be done with phpseclib as follows:
use phpseclib3\Crypt\PublicKeyLoader;
$x509pem = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAunF5aDa6HCfLMMI/MZLT
5hDk304CU+ypFMFiBjowQdUMQKYHZ+fklB7GpLxCatxYJ/hZ7rjfHH3Klq20/Y1E
bYDRopyTSfkrTzPzwsX4Ur/l25CtdQldhHCTMgwf/Ev/buBNobfzdZE+Dhdv5lQw
KtjI43lDKvAi5kEet2TFwfJcJrBiRJeEcLfVgWTXGRQn7gngWKykUu5rS83eAU1x
H9FLojQfyia89/EykiOO7/3UWwd+MATZ9HLjSx2/Lf3g2jr81eifEmYDlri/OZp4
OhZu+0Bo1LXloCTe+vmIQ2YCX7EatUOuyQMt2Vwx4uV+d/A3DP6PtMGBKpF8St4i
GwIDAQAB
-----END PUBLIC KEY-----';
$publicKey = PublicKeyLoader::load($x509pem); // import public PEM key
$xmlFormattedKey = $publicKey->toString("XML"); // export public XML key
print($xmlFormattedKey);
The output is:
<RSAKeyValue>
<Modulus>unF5aDa6HCfLMMI/MZLT5hDk304CU+ypFMFiBjowQdUMQKYHZ+fklB7GpLxCatxYJ/hZ7rjfHH3Klq20/Y1EbYDRopyTSfkrTzPzwsX4Ur/l25CtdQldhHCTMgwf/Ev/buBNobfzdZE+Dhdv5lQwKtjI43lDKvAi5kEet2TFwfJcJrBiRJeEcLfVgWTXGRQn7gngWKykUu5rS83eAU1xH9FLojQfyia89/EykiOO7/3UWwd+MATZ9HLjSx2/Lf3g2jr81eifEmYDlri/OZp4OhZu+0Bo1LXloCTe+vmIQ2YCX7EatUOuyQMt2Vwx4uV+d/A3DP6PtMGBKpF8St4iGw==</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
For key generation OpenSSL can be used as in your code. However, the exported PEM key must be imported in the phpseclib part as shown in the code above (this import is missing in your code):
// Key generation with OpenSSL
$config = array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config); // create key resource using $config
//openssl_pkey_export($res, $privKey); // export private key (PEM encoded, PKCS#8 format); not required for this example
$pubKeyDetails = openssl_pkey_get_details($res);
$x509pem = $pubKeyDetails["key"]; // export public key (PEM encoded, X.509 format)
// Key conversion with phpseclib
$publicKey = PublicKeyLoader::load($x509pem); // import public PEM key generated with OpenSSL
$xmlFormattedKey = $publicKey->toString("XML"); // export public XML key
print($xmlFormattedKey);
Alternatively, also key generation can be done with phpseclib:
use phpseclib3\Crypt\RSA;
$privateKey = RSA::createKey(2048); // generate private key
$xmlFormattedKey = $privateKey->getPublicKey()->toString("XML"); // export public XML key
print($xmlFormattedKey);
I am trying to create a JWT token. The other server is storing the public key in a single line and using that for validation.
Also, the public key being used for validation is in single line.
So, to generate the correct JWT token, what I think is I should also use the private key in a single line (may be with \n or may be without).
I am using openssl_sign to generate the token, which uses openssl_reource as key. I get that paramter from openssl_pkey_get_private.
But problem which happens in this case is, it either accepts the pem file path, or the key in PEM string format. So, if I pass the private_key as a single line, it doesn't give me the required output.
So, how can I resolve this. As I see other language libraries able to generate signature by passing private key in a single line.
In PHP the key can be formatted with line breaks or as a one-liner (with \n). Both works. In the following example I use a 512-bit encrypted RSA-key for simplicity (although in practice a larger key (>= 2048 bit) must be used for security reasons):
<?php
// Private key: 512 bit for simplicity
// Passphrase: MyPassphrase
// openssl genrsa -aes256 -out private.pem 512
$privKeyEnc = "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,8F2D6F9594B3D379BF9D9748BD174458
RP2fyz1VNBKHiCadC5B9fjxV7z7AMAqbsN2vykFfPhdUFsxlJaecEeTMT7s6IbZN
Pr80+ljLjJ0SxJiK+j8DAc/Wrf+qyYUFcWbsvOhUIPyB5ww9+mEeIERJCigsyZJ7
k/Apau/BypdC9vCXKB3wM9FcmvP1g/ZwVoXfN3TIPEfWTktvuf74yFNoIaVbZAK/
+tzAGduu9wLkr6WTq4Isqy/IPjVCp9VwH1wNnz+hjkO7oELcCpFieIvAidUMKBR9
EdexLQCimbOl2wlfRNLincK8+FDOVWx6ElFFQlhzyWQCt8ed1fdiAggKxOco4Ww2
tFjIzaO4KXlbc9JFGd9PzigpftN/aHbk3c+x0E+3q5u8eySai4vgk38s1KaE7rn/
rarCgtGxOlbbTkI3opkjIrGlrsEyexKtS23mI/Dgcco=
-----END RSA PRIVATE KEY-----";
// One-liner using \n
$privKeyEnc_1Line = "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-256-CBC,8F2D6F9594B3D379BF9D9748BD174458\n\nRP2fyz1VNBKHiCadC5B9fjxV7z7AMAqbsN2vykFfPhdUFsxlJaecEeTMT7s6IbZN\nPr80+ljLjJ0SxJiK+j8DAc/Wrf+qyYUFcWbsvOhUIPyB5ww9+mEeIERJCigsyZJ7\nk/Apau/BypdC9vCXKB3wM9FcmvP1g/ZwVoXfN3TIPEfWTktvuf74yFNoIaVbZAK/\n+tzAGduu9wLkr6WTq4Isqy/IPjVCp9VwH1wNnz+hjkO7oELcCpFieIvAidUMKBR9\nEdexLQCimbOl2wlfRNLincK8+FDOVWx6ElFFQlhzyWQCt8ed1fdiAggKxOco4Ww2\ntFjIzaO4KXlbc9JFGd9PzigpftN/aHbk3c+x0E+3q5u8eySai4vgk38s1KaE7rn/\nrarCgtGxOlbbTkI3opkjIrGlrsEyexKtS23mI/Dgcco=\n-----END RSA PRIVATE KEY-----";
// Public key:
// Passphrase: MyPassphrase
// openssl rsa -in private.pem -outform PEM -pubout -out public.pem
$pubKey = "-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMjYQLbdIVgKX1mSyKijOIpmlB9YWui1
KoCniRNHUPEsxth+o9fZXZMo1gzh9ZlFs6VLiyU7kv2+5QElOnhNzwcCAwEAAQ==
-----END PUBLIC KEY-----";
// One-liner using \n
$pubKey_1Line = "-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMjYQLbdIVgKX1mSyKijOIpmlB9YWui1\nKoCniRNHUPEsxth+o9fZXZMo1gzh9ZlFs6VLiyU7kv2+5QElOnhNzwcCAwEAAQ==\n-----END PUBLIC KEY-----";
$dataToSign = 'The quick brown fox jumps over the lazy dog.';
// Signing
//$privateKey = openssl_pkey_get_private("$privKeyEnc", "MyPassphrase"); // also works
$privateKey = openssl_pkey_get_private("$privKeyEnc_1Line", "MyPassphrase");
openssl_sign($dataToSign, $signature, $privateKey, 'sha256');
$signatureBase64 = base64_encode($signature);
print("Signature (Base64): ".$signatureBase64."<br>");
// Verifying
$publicKey = openssl_pkey_get_public("$pubKey");
//$publicKey = openssl_pkey_get_public("$pubKey_1Line"); // also works
$verified = openssl_verify($dataToSign, $signature, $publicKey,'sha256');
print("Verification: ".$verified."<br>");
/*
Output:
Signature (Base64): KVuUd+xy6at0emmhF20rbiD9lWzIN9euwKbeEm7aMvxqEkJ68HrjAoDJ37R3QGPI24woXY3TON9pahAhx+YNhQ==
Verification: 1
*/
?>
I'm basically trying to create a signature using "openssl" (PHP) and verify that using "criptografy" (PYTHON). And I'm always getting the error "InvalidSignature", which means I'm doing something wrong. I know that they are different languages and libraries but once I'm using the same algorithm for both I expected to get a valid signature. I appreciate any help.
PHP: creating public key and signature without problems
$config = array(
"digest_alg" => "sha256",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privKey);
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
error_log($pubKey);
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtXyDj9vqTGkR/ITYZ6+e
xXATzalUOdBcqee+qcb5NJ6Z5DgNdYi9lWz/4YfitYKp0EFwPzbem1zBzKbuQSko
y7zRjpmyGbw8Q6wexO4SyA44jxs75JNXMA2x22dkNKajRE5kXngBIF1ixpzCxvvc
kfyewM8C8y2iAy5j02YZYw9ysrQWJegamq6sidnMCJBtokOnPQaNJwbDQTqwrSRS
8IDy7BtBHB7F/bBwLArwxG7aLFjJ9vf2F7HpmZ3VvJa69OhY0pZMSqePQpJBIQ+2
ztIywpKkOukJz22Brqoe0ygMQzVrcYoj2MZ8CSiKUCJL6Wm9ErFXvBh/XqPWjX1t
nWdnF6qSD/2itIw18+PzCWYaoeu6w064dcbRrUQ4UOYxp69IFtrv5OHAsuWPJ27q
2IUCZ9DWWphlwhz+lI4rAb6whd2R8Sb7vEhvSz4Kd5kIjel9Dt8mJ+jGyhTjqIhP
7amgcOQLKZJfmeltYI+F0U8oJcOPhxtlxfFB1MIxPDHvCcdR93LJGgU6NboTwcpx
hnoI86xKblJmnxMxuQbUfPRU8vAuiizKVrpQS8z2k58mlxa9+hykjMcqpAvQ6STM
vLswdj0j9aqyv6I94z2Q2Lgcuoh7xSJcLhKN9QGaarUqjAY/zoZPiDnCxXlnVrav
BMyQZ9PqbsaHsd7pVVpuW8MCAwEAAQ==
-----END PUBLIC KEY-----
$data = 'oi';
$pkeyid = openssl_pkey_get_private($privKey);
openssl_sign($data, $signature, $pkeyid);
error_log(base64_encode($signature));
MoUZzfaHCwME2mmxJnMBQWgo+lTLK2QfpfD+5IEnSwi0wmRtgZgFl7IGsWYlTO+zTQCcB/aKg91CMClmb5P2jEtOkY3ie2pNflEIsc3aGqfWoVpHJUMoft+4hytzgMszqwgbJdo6eac7zIxlrzmeb4jb58APtc4aaLLQru2Gga9oPRyCqbXrD0TXnQ6GzjDNGwi6wP30NU9KaHWaGfeq1WSqsAIaIbi2oG4MeWJYX6SOB/CX1Jg8SJYzWQahpJeybE4Z8fR6ncuvfbjp9aet1aKsPB/DFPQ5VFaAS4oItVb0Ha4wkQ8YgJu5fEUK7X9KzuOwidja5RLZtwDPa0bBSveCw9D8FUsguilaoIu7ueDPTRueK4bQkYstOc2OvVlzInukyOzFXVgZsiV23FTHrQ5FqHd9nCUbfuhgrMqHRYQmRFUgDaeyY+B5ve3bQ4lT3qm282ngKi8AZ+clB0VeaFiQxpF8SCCRMu0bX3dsQMaXRUeSVDipf3ZMABl9xXbzEjqXoJzuvC6tCnEv8K3HzKbjz2S1876eGy7opIixaUMwDu9QOiPoSiFUY/xCsX8D1Im8Mv4eyzWNV3FL1U/GS3LZzkq/NuJdB7wjCib3ieHaYX/bvTpmAp/oO0+vbI2pzq9w71cpqQpsNsOZSGkgY2q1sO6u0I5jCFScdJVbJl0=
PYTHON: InvalidSignature error
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives.serialization import load_pem_public_key
signature= 'MoUZzfaHCwME2mmxJnMBQWgo+lTLK2QfpfD+5IEnSwi0wmRtgZgFl7IGsWYlTO+zTQCcB/aKg91CMClmb5P2jEtOkY3ie2pNflEIsc3aGqfWoVpHJUMoft+4hytzgMszqwgbJdo6eac7zIxlrzmeb4jb58APtc4aaLLQru2Gga9oPRyCqbXrD0TXnQ6GzjDNGwi6wP30NU9KaHWaGfeq1WSqsAIaIbi2oG4MeWJYX6SOB/CX1Jg8SJYzWQahpJeybE4Z8fR6ncuvfbjp9aet1aKsPB/DFPQ5VFaAS4oItVb0Ha4wkQ8YgJu5fEUK7X9KzuOwidja5RLZtwDPa0bBSveCw9D8FUsguilaoIu7ueDPTRueK4bQkYstOc2OvVlzInukyOzFXVgZsiV23FTHrQ5FqHd9nCUbfuhgrMqHRYQmRFUgDaeyY+B5ve3bQ4lT3qm282ngKi8AZ+clB0VeaFiQxpF8SCCRMu0bX3dsQMaXRUeSVDipf3ZMABl9xXbzEjqXoJzuvC6tCnEv8K3HzKbjz2S1876eGy7opIixaUMwDu9QOiPoSiFUY/xCsX8D1Im8Mv4eyzWNV3FL1U/GS3LZzkq/NuJdB7wjCib3ieHaYX/bvTpmAp/oO0+vbI2pzq9w71cpqQpsNsOZSGkgY2q1sO6u0I5jCFScdJVbJl0='
decoded = base64.b64decode(signature)
plaintextMessage="oi"
# /tmp/public contains the public key
alicePubKey = load_pem_public_key(open('/tmp/public', 'rb').read(),default_backend())
ciphertext = alicePubKey.verify(
decoded,
plaintextMessage,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA256()
)
It's pretty clear that your PHP code:
Signed using RSA with SHA1, not SHA256
Used PKCS#1 version 1.5 padding, not PSS
It looks like you just copy&pasted your code from the cryptography package documentation.
Thus the following python snippet should verify:
ciphertext = alicePubKey.verify(
decoded,
b'oi',
padding.PKCS1v15(),
hashes.SHA1()
)
PSS and SHA-256 are better choices, so you should investigate modifying your PHP code to use those instead of modifying your python code.
As James said, the function openssl_sign was using SHA1 by default, what could be solved with the parameter OPENSSL_ALGO_SHA256.
So I did these changes:
PHP
openssl_sign($data, $signature, $pkeyid, OPENSSL_ALGO_SHA256);
Python
ciphertext = alicePubKey.verify(
decoded,
plaintextMessage,
padding.PKCS1v15(),
hashes.SHA256()
)
I generated on server side a pair public/private keys using phpseclib like
include 'Crypt/RSA.php';
$rsa = new Crypt_RSA();
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
extract($rsa->createKey());
echo $privatekey;
echo "\n\n\n";
echo $publickey;
Now I want import on client side Public key using Java Bouncy Castle engine.
Here my Public key
-----BEGIN PUBLIC KEY-----
MIGJAoGBAJEGAmaQejDgJaCg/B5+g68arqpMpl6jZ9+p8TBzNRIq+Ygt/n3iqz+pAtltrlRnmqSD
svx0LMluw1wXezQ1pz2tTJTEhg6b69Qui0o//W5UDfle4yOyAHaOs8MD5nubJjXFU8vGiEdektET
jgKqiSr5TBgZoHy+YDWpd4yTemXVAgMBAAE=
-----END PUBLIC KEY-----
But I can do it. I tried to do it several ways but I always get errors.
AsymmetricKeyParameter publicKey =
(AsymmetricKeyParameter) PublicKeyFactory.createKey(b64.decodeBuffer(key));
AsymmetricKeyParameter publicKey =
(AsymmetricKeyParameter) PublicKeyFactory.createKey(key.getBytes())
Also
PEMReader pemReader = new org.bouncycastle.openssl.PEMReader (reader);
PemObject pem = pemReader.readPemObject();
All these ways generate error.
How should I import Public key using Java Bouncy Castle engine?
I found solution
key = key.replaceAll("PUBLIC KEY", "RSA PUBLIC KEY");
final Reader reader = new StringReader(key);
PEMReader pemReader = new PEMReader(reader);
Object obj = pemReader.readObject();
pemReader.close();
BCRSAPublicKey bcPublicKey = (BCRSAPublicKey) obj;
AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter) PublicKeyFactory.createKey(bcPublicKey.getEncoded());
AsymmetricBlockCipher e = new RSAEngine();
e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
e.init(true, publicKey);
byte[] messageBytes = inputData.getBytes();
encryptedData = e.processBlock(messageBytes, 0, messageBytes.length);
Now i can encrypt on Java side and decrypt on Server (PHP) side
Might be worthwhile to try with the latest Git version of phpseclib. Quoting from a semi-recent commit:
https://github.com/phpseclib/phpseclib/commit/2f8d1055ea5a6b06cd7a40eb85661ba688a31320
Quoting from it, the commit "[makes] Crypt_RSA's public keys compatible with OpenSSL".