我需要帮助解决这个问题。在互联网上,我发现很多例子用android加密android和用php解密。在我的情况下,我在android上生成密钥对,发送php公钥,然后在PHP中使用该密钥加密,并使用私钥在android中解密。 我在Android中使用Spongy Castle,在php中使用Phpseclib。
在android中我使用类org.spongycastle.util.encoders.Base64
生成密钥对:
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
generator.initialize(1024);
KeyPair kPair = generator.generateKeyPair();
byte[] privateKeyEnc = kPair.getPrivate().getEncoded();
byte[] publicKeyEnc = kPair.getPublic().getEncoded();
String publicKey = new String(Base64.encode(publicKeyEnc)); //this key is send to php
String privateKey = new String(Base64.encode(privateKeyEnc));
在php中加密:
$message = "...";
$publicKey = "..."; //key received from android
$rsa = new Crypt_RSA();
$rsa->setHash('sha1');
$rsa->setMGFHash('sha1');
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$key = "-----BEGIN PUBLIC KEY-----\n" . base64_decode($publicKey)
. '-----END PUBLIC KEY-----';
$rsa->loadKey($key);
$messageEncrypt = base64_encode($rsa->encrypt($message)); //this message is send to android
在android中解密:
String message = "..."; //this received from php
String privateKey = "..."; //this key was generated in android
byte[] privateKeyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA", "SC");
PrivateKey priv = fact.generatePrivate(keySpec);
Cipher rsaCipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "SC");
rsaCipher.init(Cipher.DECRYPT_MODE, priv);
byte[] messageDecryptBytes = rsaCipher.doFinal(message);
String messageDecrypt = new String(Base64.encode(messageDecryptBytes));
在android中我收到以下错误:
异常:java.lang.ArrayIndexOutOfBoundsException:RSA块的数据太多
当我读到错误的原因是要解密的消息中的字节不遵循rsa的预期格式。如果是这种情况,则加密时错误将在php中。
我可以成功运行android加密并在php中解密。但是我没有在php中找到使用在android上生成的公钥进行加密的示例。