我试图将RSA公钥从PHP发送到Java(Android)。我的PHP代码看起来像这样:
function __construct() {
$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);
// Code to Generate the public key and private key
$keys = $rsa->createKey(1024);
extract($keys);
// Base 64 encode Public and Private key
$this->rsa = $rsa;
$this->keys = $keys;
$this->publicKeyBase = base64_encode($publickey);
$this->privateKeyBase = base64_encode($privatekey);
}
我将$this->publicKeyBase
发送到我的Android应用。在Java中,我得到了这样的编码字符串:
LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tDQpNSUdKQW9HQkFMQzluUkdhVGsybzlJTW5YVW0vWWRVMHMrTFplc09GUi9VYkU2K21hWDlwbGIwRW11RzZacHBMDQpoV2dRbUNBYmV6aW9ScHZNL0lVZHZWczZ6ZmFKaDRGTnFaRXo0cWd0V0ovaFpUU2RudlFIMlI3cWF0TEY0c0ZSDQpDbWNNVDZBdnYvdDJnR1liMW4vY1lhb01ralNOd1RFdTJBSU45djg0Skk2ZWhmOGNST0RMQWdNQkFBRT0NCi0tLS0tRU5EIFJTQSBQVUJMSUMgS0VZLS0tLS0=
解码后,它看起来像这样:
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALC9nRGaTk2o9IMnXUm/YdU0s+LZesOFR/UbE6+maX9plb0EmuG6ZppL
hWgQmCAbezioRpvM/IUdvVs6zfaJh4FNqZEz4qgtWJ/hZTSdnvQH2R7qatLF4sFR
CmcMT6Avv/t2gGYb1n/cYaoMkjSNwTEu2AIN9v84JI6ehf8cRODLAgMBAAE=
-----END RSA PUBLIC KEY-----
如何将其转换为可在Android App中使用的公钥。在网上看过很多例子,但它们不起作用,我的java代码(下面)似乎也不起作用。任何可能的解决方案?
private static PublicKey getPublicKeyFromPemFormat(String PEMString, boolean isFilePath) throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
BufferedReader pemReader = null;
if (isFilePath) {
pemReader = new BufferedReader(new InputStreamReader(
new FileInputStream(PEMString)));
} else {
pemReader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(PEMString.getBytes("UTF-8"))));
}
StringBuffer content = new StringBuffer();
String line = null;
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----BEGIN RSA PUBLIC KEY-----") != -1) {
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----END RSA PUBLIC KEY-----") != -1) {
break;
}
content.append(line.trim());
}
break;
}
}
if (line == null) {
throw new IOException("PUBLIC KEY" + " not found");
}
Log.i("PUBLIC KEY: ", "PEM content = : " + content.toString());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT)));
}
new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT)) throws an Invalid KeySpec Exception.
答案 0 :(得分:2)
文档有点令人困惑,但从第950行开始查看source code方法_convertPublicKey($n, $e)
,看来如果$publicKeyFormat == PUBLIC_FORMAT_PKCS8
那么输出格式应该是兼容的格式使用Java的X509EncodedKeySpec类。