PhpSeclib & # 8596; Bouncycastle rsa

I generated a server-side pair of 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 to import the public key on the client side using the Java Bouncy Castle engine.
Here is 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 this in several ways, but always get errors.

 AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter) PublicKeyFactory.createKey(b64.decodeBuffer(key)); AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter) PublicKeyFactory.createKey(key.getBytes()) 

Besides

 PEMReader pemReader = new org.bouncycastle.openssl.PEMReader (reader); PemObject pem = pemReader.readPemObject(); 

All of these methods generate an error.

How do I import a public key using the Java Bouncy Castle engine?

+1
source share
2 answers

I found a 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 the Java side and decrypt on the server side (PHP)

+1
source

It might be worth a try with the latest phpclib version of Git. Quoting using recent commit:

https://github.com/phpseclib/phpseclib/commit/2f8d1055ea5a6b06cd7a40eb85661ba688a31320

To quote from this, commit "[makes] the Crypt_RSA public keys compatible with OpenSSL."

0
source

Source: https://habr.com/ru/post/975273/


All Articles