【发布时间】:2016-10-30 15:50:43
【问题描述】:
我正在尝试解密从服务器发送到 android 应用程序的文本。 在 PHP 上,我有以下内容:
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$key = "-----BEGIN PUBLIC KEY-----\n" . ($PublicKey)
. '-----END PUBLIC KEY-----';
$rsa->loadKey($key);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$imageEncrypt = base64_encode($rsa->encrypt($base64));
编码和加密工作良好。 当我将加密文本发送到 android 时,我无法解密。我使用了代码:
public static String decryptString(String alias,String cipherText) {
try {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
// RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");
output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), output);
ArrayList<Byte> values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
String finalText = new String(bytes, 0, bytes.length, "UTF-8");
return finalText;
//decryptedText.setText(finalText);
} catch (Exception e) {
Toast.makeText(context, "Exception " + e.getMessage() + " occured", Toast.LENGTH_LONG).show();
Log.e("DecryptStringTAG", Log.getStackTraceString(e));
}
return "EMPTY";
}
错误是:
java.io.IOException: Error while finalizing cipher
Caused by: javax.crypto.IllegalBlockSizeException
奇怪的是,当我尝试从 PHP 发送类似“Hello”的消息时,android 成功解密了它。但是当我发送加密图像时,我得到了声明的错误。
我一直在努力寻找错误。
有什么帮助吗?
谢谢
【问题讨论】:
-
您确实意识到 RSA 只能加密比密钥长度更短的数据,该数据通常使用对称算法(如 AES)加密。另一件事是为什么选择 RSA,是否需要公钥/私钥对?。
-
感谢您的回复。其实我不知道这件事。至于为什么要使用 RSA,因为架构要求如此。我不得不使用公钥加密。有没有办法解决这个问题?
标签: php android encryption cryptography rsa