'Decrypt AES key with RSA got invalid key length error Occasionally

We encrypt the AES key through RSA method in Java on the client-side, aka android mobile phone.

class Encryptor {
    private static String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";

    public Init() {
        this.rsaEncCipher = Cipher.gtInstance(RSA_ALGORITHM);
        this.rsaEncCipher.init(Cipher.ENCRYPT_MODE, public_key)
    }

    public byte[] rsaPublicEncrypt(byte[] content) {
        try {
            return this.rsaEncCipher.doFinal(content);
        } catch(Exception a) {
            //
        }
    }
}


JsonObject json = new JsonObject();

byte[] key = new byte[16];
random.nextBytes(key);

byte[] encryptedContent = encryptor.aesEncrypt(key, content.getBytes())
byte[] encryptedKey = encryptor.rsaPublicEncrypt(key);

json.addProperty("key", Base64.encodeToString(encryptedKey, Base64.DEFAULT));
json.addProperty("content", Base64.encodeToString(encryptedContent, Base64.DEFAULT));

And decrypted the AES key with RSA in Node.js on the server side

function  decryptAes(key, cipherContent) {
    var decipher = crypto.createDecipheriv("AES-128-CBC", key, "AndroidAESEncrypt");
    let plainText = decipher.update(cipherContent, 'base64', 'utf8');
    return plainText += decipher.final('utf8');
}

function descrypt(key, content) {
    const contentBuffer = buffer.from(key, 'base64');
    const keyBuffer = Buffer.from(key, 'base64');
    const aesKey = crypto.privateDecrypt({
                    key: privateKey,
                    padding: crypto.constants.RSA_PKCS1_PADDING
                }, keyBuffer);;

    console.log(aesKey.length)

    const rawContent = decryptAes(aesKey, contentBuffer).toString('base64')
}

Most of the time, the encrypt/decrypt mechanism works well and the length of aesKey is 16. Occasionally, we met the error invalid key length from AES decrypt, and the length of aesKey is 32. We try to decrypt the contentBuffer with the first 16 bytes of aesKey whose length is 32, the function decryptAes works well. It is so weird.

Is there anyone who met the same weird issue before?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source