// Ripped from https://github.com/Ch0pin/medusa/ and modified to fit Androguard packets

colorLog("[+] LOADING ENCRYPTION/KEYSTORE.JS", { c: Color.Red });

var keystore = Java.use("java.security.KeyStore");

keystore.containsAlias.overload("java.lang.String").implementation = function (
    alias,
) {
    var ret = this.containsAlias(alias);
    agPacket({
        alias: alias,
        ret: ret,
    }).send();

    return ret;
};

keystore.getKey.overload("java.lang.String", "[C").implementation = function (
    alias,
    password,
) {
    var ret = this.getKey(alias, password);
    agPacket({
        alias: alias,
        password: password,
        algorithm: ret.getAlgorithm(),
        encoded: ret.getEncoded(),
        ret: ret,
    }).send();

    return ret;
};

keystore.load.overload("java.io.InputStream", "[C").implementation = function (
    stream,
    charArray,
) {
    /* sometimes this happen, I have no idea why, tho... */
    if (stream == null) {
        /* just to avoid interfering with app's flow */
        this.load(stream, charArray);
        return;
    }

    var hexString = readStreamToHex(stream);

    agPacket({
        certType: this.getType(),
        password: charArray,
        cert: hexString,
    }).send();

    /* call the original implementation of 'load' */
    this.load(stream, charArray);
    /* no need to return anything */
};
