问题
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