Abin K Paul
Abin K Paul

Reputation: 181

Calling a method of a Java object passed as argument to hooked function in Frida

I am trying to obtain the SecretKey passed to the decryptAesCipherText function. I hooked the function in Frida to try to print out the arguments when the method is called but since SecretKey is an object, all attempts to print it out give output as [object Object]. However the SecretKey object has a method getEncoded() which will return a byte array which can be printed out in hex format. How can I call this method from Frida and get the result?

The java function, I am hooking to is given below

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

private byte[] decryptAesCipherText(SecretKey secretKey, byte[] bArr) {
        Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
        instance.init(2, secretKey);
        return decryptCipherText(instance, bArr);
}



The javascript snippet (incomplete) to hook the function

var target_class = Java.use('com.reactlibrary.securekeystore.RNSecureKeyStoreModule');

target_class.decryptAesCipherText.overload('javax.crypto.SecretKey','[B').implementation = function(key, array){
        console.log("Inside decrypt aes");

        //Call getEncoded method on key to get byte array

        var ret = my_class.decryptAesCipherText.overload('javax.crypto.SecretKey','[B').call(this, key, array);
        return ret;
}

Upvotes: 4

Views: 6622

Answers (1)

Robert
Robert

Reputation: 42585

It seems like you can't call getEncoded on the javax.crypto.SecretKey interface.

Usually the SecretKey parameter is of type javax.crypto.spec.SecretKeySpec and if you type cast the key parameter to SecretKeySpec you can can call getEncoded() and print the used key:

function encodeHex(byteArray) {
    const HexClass = Java.use('org.apache.commons.codec.binary.Hex');
    const StringClass = Java.use('java.lang.String');
    const hexChars = HexClass.encodeHex(byteArray);
    return StringClass.$new(hexChars).toString();
}

Java.perform(function x() {
    const target_class = Java.use('com.example.myapplication.MainActivity');
    target_class.decryptAesCipherText.overload('javax.crypto.SecretKey', '[B').implementation = function (key, array) {
        console.log("Inside decrypt aes");

        const secretKeySpec = Java.cast(key, Java.use('javax.crypto.spec.SecretKeySpec'));
        const encodedKey = secretKeySpec.getEncoded();

        // print the key bytes as hex value
        console.log("KEY: " + encodeHex(encodedKey));

        var ret = my_class.decryptAesCipherText.overload('javax.crypto.SecretKey', '[B').call(this, key, array);
        return ret;
    }

});

Upvotes: 5

Related Questions