android - How to modify Apk in .NET - Stack Overflow

I need to do something really simpleI have to add a json file to an ApkSigned Apk is stored in azure

I need to do something really simple

I have to add a json file to an Apk

Signed Apk is stored in azure blob container

Apk modification happens in .NET using apktool and apksigner

I can get the file created and the Apk built and signed, but then the Apk becomes invalid on the android device

Now I am stuck

Here is the code for modifying the already signed APK

public static async Task<MethodResult<byte[]>> ModifyAndResignApk(byte[] apkBytes, string appId, string groupId)
{
    var result = new MethodResult<byte[]>();

    string apkToolsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Apk Tools");
    string apkToolPath = Path.Combine(apkToolsFolder, "apktool.jar");
    string apkSignerPath = Path.Combine(apkToolsFolder, "apksigner.bat");
    string keystorePath = Path.Combine(apkToolsFolder, "androidKeyStore.keystore");

    string tempFolder = Path.Combine(Path.GetTempPath(), "apk_modification_" + Guid.NewGuid());
    string extractedApkFolder = Path.Combine(tempFolder, "extracted");
    string signedApkPath = Path.Combine(tempFolder, "signed.apk");
    string tempApkPath = Path.Combine(tempFolder, "temp.apk");
    string unsignedApkPath = Path.Combine(extractedApkFolder, "dist", "unsigned.apk");
    string jsonFilePath = Path.Combine(extractedApkFolder, "assets", "config.json");

    string keystorePassword = "myPassword";
    string keyPassword = "myPassword";

    try
    {
        Directory.CreateDirectory(extractedApkFolder);
        await File.WriteAllBytesAsync(tempApkPath, apkBytes);

        // Step 1: Decompile APK
        if (!await RunProcessAsync("java", $"-jar \"{apkToolPath}\" d \"{tempApkPath}\" -o \"{extractedApkFolder}\" --force"))
            throw new Exception("Failed to decompile APK");

        // Step 2: Add config.json
        Directory.CreateDirectory(Path.GetDirectoryName(jsonFilePath) ?? extractedApkFolder); // Ensure assets folder exists
        var config = new { appId, groupId };
        string jsonContent = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
        await File.WriteAllTextAsync(jsonFilePath, jsonContent);

        // Step 3: Rebuild APK
        if (!await RunProcessAsync("java", $"-Xmx1024M -jar \"{apkToolPath}\" b \"{extractedApkFolder}\" -o \"{unsignedApkPath}\""))
            throw new Exception("Failed to rebuild APK");

        // Step 4: Sign the APK
        if (!await RunProcessAsync(apkSignerPath, $"sign --ks \"{keystorePath}\" --ks-pass pass:{keystorePassword} --key-pass pass:{keyPassword} --out \"{signedApkPath}\" \"{unsignedApkPath}\""))
            throw new Exception("Failed to sign APK");

        return result.Success(await File.ReadAllBytesAsync(signedApkPath));
    }
    catch (Exception e)
    {
        return result.Fail(e, "Failed to modify and resign APK");
    }
    finally
    {
        await Task.Delay(500); // Ensure no lingering file locks
        if (Directory.Exists(tempFolder))
        {
            Directory.Delete(tempFolder, true);
        }
    }
}

private static async Task<bool> RunProcessAsync(string fileName, string arguments)
{
    var process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = fileName,
            Arguments = arguments,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        }
    };

    process.Start();
    await process.WaitForExitAsync();

    string output = await process.StandardOutput.ReadToEndAsync();
    string error = await process.StandardError.ReadToEndAsync();

    Console.WriteLine(output);
    if (!string.IsNullOrWhiteSpace(error))
        Console.WriteLine($"Error: {error}");

    return process.ExitCode == 0;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744936975a4602086.html

相关推荐

  • android - How to modify Apk in .NET - Stack Overflow

    I need to do something really simpleI have to add a json file to an ApkSigned Apk is stored in azure

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信