我正在尝试在 Android 端加密数据,并在 PHP 端解密数据。我在 PHP 中使用 phpseclib 生成公钥/私钥。
在生成密钥之后,我得到了PHP端的公钥:
然后我将其编码为base64,得到了这个base64编码的密钥。
我将它复制到 Android 端用于加密数据,但是出现了“InvalidKeySpecException”错误。
Android 端代码:
在生成密钥之后,我得到了PHP端的公钥:
-----BEGIN RSA PUBLIC KEY-----".
"MIGJAoGBAKks62Itns2uU/dVZJ4kCkMinHgyeh/rdMD53a4Zu2a76OIJvdSZ8q4c".
"YTWvPj0giefVtMc7tV4c6AAw04jyIfmCTvcQUlHI+sspHxXDlQTagNoxCuA29b5L".
"9MKO6Ok0LwF9rGgTywC1heNEulZz9ISn9FQDazJT+Bd9cnNOrJRdAgMBAAE=".
"-----END RSA PUBLIC KEY-----
然后我将其编码为base64,得到了这个base64编码的密钥。
LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tTUlHSkFvR0JBS2tzNjJJdG5zMnVVL2RWWko0a0NrTWluSGd5ZWgvcmRNRDUzYTRadTJhNzZPSUp2ZFNaOHE0Y1lUV3ZQajBnaWVmVnRNYzd0VjRjNkFBdzA0anlJZm1DVHZjUVVsSEkrc3NwSHhYRGxRVGFnTm94Q3VBMjliNUw5TUtPNk9rMEx3RjlyR2dUeXdDMWhlTkV1bFp6OUlTbjlGUURhekpUK0JkOWNuTk9ySlJkQWdNQkFBRT0tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0t
我将它复制到 Android 端用于加密数据,但是出现了“InvalidKeySpecException”错误。
Android 端代码:
public static byte[] encrypt(String text) {
byte[] encodedPublicKey= Base64.decode("LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tTUlHSkFvR0JBS2tzNjJJdG5zMnVVL2RWWko0a0NrTWluSGd5ZWgvcmRNRDUzYTRadTJhNzZPSUp2ZFNaOHE0Y1lUV3ZQajBnaWVmVnRNYzd0VjRjNkFBdzA0anlJZm1DVHZjUVVsSEkrc3NwSHhYRGxRVGFnTm94Q3VBMjliNUw5TUtPNk9rMEx3RjlyR2dUeXdDMWhlTkV1bFp6OUlTbjlGUURhekpUK0JkOWNuTk9ySlJkQWdNQkFBRT0tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0t", Base64.DEFAULT);
PublicKey publicKey=null;
KeyFactory keyFactory = null;
try {
keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
publicKey = keyFactory.generatePublic(publicKeySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (InvalidKeySpecException e) {
e.printStackTrace();
}
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
$rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_XML);
。然后提取模数和指数,对它们进行 Base64 解码并将它们放入一个RSAPublicKeySpec
实例中。 - President James K. Polk$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_XML); $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_XML); extract($rsa->createKey());
,并获得了以下密钥:<RSAKeyValue> <Modulus>uRe18YPb3x8Moqe6E9M2f4GTCQNm5i7lm5MrvmmiW0hjC+SG0vxXOcWpDegwQIlfWfN3SUPJUxn4YeaAqX4Z2Xx2N9elgsPUM6EYYMl+dforjsBpk0uc1EvncYahpg0si0I7MnXqLD6SmVM6OX2M8XvTkKbYu2GvZ6zlPrMe3B8=</Modulus> <Exponent>AQAB</Exponent> </RSAKeyValue>
请问如何处理并在Android中使用它?能否提供相关代码? - Khaled Awad