在Android中解密Base64加密的图像


Decrypting a Base64 encrypted image in Android

我试图解密从服务器发送到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非对称密钥加密也就是公钥加密所使用的,也就是说RSA本质上就是公钥加密。如果你必须使用公钥/私钥对加密,答案是混合加密,类似于SSL所做的。

创建一个随机对称密钥,用它来用AES加密数据。然后用RSA公钥对对称密钥进行加密。

在解密时,首先用RSA私钥解密对称密钥,然后用对称AES解密数据。

如果你正在寻找安全的加密,你真的需要有人谁是一个领域的专家,至少设计和审查实现。安全是很难做到正确的,如果不正确,就没有提供任何安全。