本文介绍了PhpSeclib<->弹力城堡RSA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在服务器端使用phpseclib生成了一对公钥/私钥,
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;
现在我想在客户端使用Java Bouncy Castle引擎导入公钥。
这里是我的公钥
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())
也
PEMReader pemReader = new org.bouncycastle.openssl.PEMReader (reader);
PemObject pem = pemReader.readPemObject();
所有这些方式都会产生错误。
All these ways generate error.
我应该如何使用Java Bouncy Castle引擎导入公钥?
How should I import Public key using Java Bouncy Castle engine?
推荐答案
我找到了解决方法
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);
现在我可以在Java端进行加密并在Server(PHP)端进行解密
Now i can encrypt on Java side and decrypt on Server (PHP) side
这篇关于PhpSeclib<->弹力城堡RSA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!