PhpSeclib <-> BouncyCastle RSA

我是研究僧i 提交于 2019-12-11 04:27:30

问题


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?


回答1:


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




回答2:


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".



来源:https://stackoverflow.com/questions/13229751/phpseclib-bouncycastle-rsa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!