public string GetAPKPackageName(String apk)
        {
            this.Dispatcher.Invoke(() =>
            {
                txtbox.AppendText("\n\nGetting APK package name");
            });
            Stopwatch s         = Stopwatch.StartNew();
            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = new ApkInfo();

            try
            {
                ZipArchive a = ZipFile.OpenRead(apk);
                a.GetEntry("AndroidManifest.xml").ExtractToFile(exe + "Androidmanifest.xml", true);
                a.GetEntry("resources.arsc").ExtractToFile(exe + "resources.arsc", true);
                info = apkReader.extractInfo(File.ReadAllBytes(exe + "AndroidManifest.xml"), File.ReadAllBytes(exe + "resources.arsc"));
            }
            catch (Exception e)
            {
                this.Dispatcher.Invoke(() =>
                {
                    txtbox.AppendText("\n\nAn Error occured while getting the APK Version:\n" + e.ToString() + "\n\nYour APK may be corrupted.Please get a fresh copy of it and try again. If you used Auto downgrade then try again.");
                    txtbox.ScrollToEnd();
                });
            };
            this.Dispatcher.Invoke(() =>
            {
                s.Stop();
                txtbox.AppendText("\nGot APK package name (" + info.packageName + ") in " + s.ElapsedMilliseconds + " ms");
                txtbox.ScrollToEnd();
            });
            return(info.packageName);
        }
Example #2
0
        private ApkInfo GetAndroidInfo(string path)
        {
            byte[] manifestData  = null;
            byte[] resourcesData = null;
            string manifestPath  = SearchPathToFile("AndroidManifest.xml", path);

            if (manifestPath == "")
            {
                Logger.WriteLog("Cannot search AndroidManifest.xml file", LogLevel.Usual);
                return(null);
            }
            string resourcesPath = SearchPathToFile("resources.arsc", path);

            if (resourcesPath == "")
            {
                Logger.WriteLog("Cannot search resources.arsc file", LogLevel.Usual);
                return(null);
            }
            manifestData  = File.ReadAllBytes(manifestPath);
            resourcesData = File.ReadAllBytes(resourcesPath);
            if (manifestData == null || resourcesData == null)
            {
                return(null);
            }
            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);

            Logger.WriteLog("Get android info from archive", LogLevel.Usual);
            return(info);
        }
Example #3
0
 private ApkInfo GetAndroidInfo(string pathDirectoryAPK)
 {
     if (!string.IsNullOrEmpty(pathDirectoryAPK))
     {
         string manifestPath = SearchPathToFile("AndroidManifest.xml", pathDirectoryAPK);
         if (!string.IsNullOrEmpty(manifestPath))
         {
             string resourcesPath = SearchPathToFile("resources.arsc", pathDirectoryAPK);
             if (!string.IsNullOrEmpty(resourcesPath))
             {
                 byte[] manifestData  = File.ReadAllBytes(manifestPath);
                 byte[] resourcesData = File.ReadAllBytes(resourcesPath);
                 if (manifestData != null || resourcesData != null)
                 {
                     ApkReader apkReader = new ApkReader();
                     ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);
                     Log.Info("Get android info from archive.");
                     return(info);
                 }
             }
             else
             {
                 Log.Error("Can't search resources.arsc file.");
             }
         }
         else
         {
             Log.Error("Can't search AndroidManifest.xml file.");
         }
     }
     return(null);
 }
Example #4
0
        /// <summary>
        /// 解析Apk
        /// </summary>
        public void ApkAnalysis()
        {
            try
            {
                var reader  = new ApkReader();
                var ApkPath = $@"{ApkSite}{Gnpy}\{AppSrc}";
                var Apk     = string.Empty;
                var root    = new DirectoryInfo(ApkPath);
                foreach (var t in root.GetFiles())
                {
                    if (Path.GetExtension(t.Name) == ".apk")
                    {
                        Apk     = t.FullName;
                        ApkName = t.Name;
                    }
                }

                var info = reader.Read(Apk);
                ApkPackage = info.PackageName;
                ApkVersion = info.VersionName;

                DirFile.Copy($@"{ApkSite}{Gnpy}\type1.png", $@"{ApkPath}\{Gnpy}.png");
            }
            catch (Exception ex)
            {
                ApkName = "NoAPKUploaded";

                ApkPackage = string.Empty;
                ApkVersion = string.Empty;
                //MessageBox.Show(ex.ToString());
            }
        }
Example #5
0
        private static void Main(string[] args)
        {
            var reader = new ApkReader();
            var info   = reader.Read(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "com.qihoo.magic.apk"));
            var json   = JsonConvert.SerializeObject(info, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented
            });

            Console.WriteLine(json);
            Console.ReadLine();
        }
Example #6
0
        private void SelectAPK(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            packageNameLBL.Text    = "Package Name: LENDO ARQUIVO";
            openFileDialog1.Filter = "APK Files|*.APK";
            openFileDialog1.Title  = "Selecione um arquivo .APK";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                NomeAPK = openFileDialog1.FileName;
                using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(openFileDialog1.FileName)))
                {
                    using (var filestream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read))
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                        ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                        try
                        {
                            while ((item = zip.GetNextEntry()) != null)
                            {
                                if (item.Name.ToLower() == "androidmanifest.xml")
                                {
                                    manifestData = new byte[50 * 1024];
                                    using (Stream strm = zipfile.GetInputStream(item))
                                    {
                                        strm.Read(manifestData, 0, manifestData.Length);
                                    }
                                }
                                if (item.Name.ToLower() == "resources.arsc")
                                {
                                    using (Stream strm = zipfile.GetInputStream(item))
                                    {
                                        using (BinaryReader s = new BinaryReader(strm))
                                        {
                                            resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                ApkReader apkReader = new ApkReader();
                ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);
                packageNameLBL.Text   = "Package Name: " + info.packageName;
                versionLBL.Text       = "Version: " + info.versionName;
                installAPKBTN.Enabled = true;
            }
        }
        public static ApkInfo ReadApkFromPath(string path)
        {
            NativeMethods.Log("ReadApkFromPath: " + path);
            byte[] manifestData  = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }
                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                }
                            }
                        }
                    }
                }
            }

            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);

            return(info);
        }
Example #8
0
        public async Task CopyAPKToLocalStorage(StorageFile sf)
        {
            apkName = sf.Name.Replace(".apk", "");

            appsRoot = await localFolder.CreateFolderAsync("Apps", CreationCollisionOption.OpenIfExists);

            localAppRoot = await appsRoot.CreateFolderAsync(apkName, CreationCollisionOption.GenerateUniqueName);

            apkName = localAppRoot.Name;
            StorageFile copiedFile = await sf.CopyAsync(appsRoot, apkName + ".apk");

            apkFile = copiedFile;

            try
            {
                ZipFile.ExtractToDirectory(copiedFile.Path, localAppRoot.Path);

                try
                {
                    StorageFile manifestFile = await localAppRoot.GetFileAsync("AndroidManifest.xml");

                    StorageFile resFile = await localAppRoot.GetFileAsync("resources.arsc");

                    byte[] manifestBytes = await Disassembly.Util.ReadFile(manifestFile);

                    byte[] resBytes = await Disassembly.Util.ReadFile(resFile);

                    ApkReader apkReader = new ApkReader();
                    ApkInfo   appinfo   = apkReader.extractInfo(manifestBytes, resBytes);
                    metadata = appinfo;

                    appIcon = GetAppIcon();

                    InvokeLoadEvent();

                    resFolder = await localAppRoot.GetFolderAsync("res");

                    //manifest = new Manifest(manifestFile);

                    /*if (localAppRoot.GetFileAsync("apktool.yml") != null)
                     * {
                     *  manifest = new Manifest(manifestFile, true);
                     * }
                     * else
                     * {
                     *  manifest = new Manifest(manifestFile);
                     * }*/
                    //manifest = new Manifest(manifestFile);

                    //StorageFile resFile = await localAppRoot.GetFileAsync("resources.arsc");
                    //resources = new Resources(resFile);
                }
                catch (System.IO.FileNotFoundException fnfEx)
                {
                    var dialog = new MessageDialog($"Not a valid APK file. Please try a different APK file. \n\n{fnfEx.Message}");
                    await dialog.ShowAsync();

                    //Provided APK is not valid, purge from app data
                    await localAppRoot.DeleteAsync();

                    await copiedFile.DeleteAsync();

                    //Go home


                    return;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
            }

            //Debug.WriteLine(localAppRoot.Path);

            //StorageFile manifestFile = await localAppRoot.GetFileAsync("AndroidManifest.xml");

            //manifest = new Manifest(manifestFile);
        }
Example #9
0
        public async Task GetAPKInfoFromLocalAppFolder()
        {
            StorageFile manifestFile = await localAppRoot.GetFileAsync("AndroidManifest.old");

            StorageFile resFile = await localAppRoot.GetFileAsync("resources.arsc");

            resFolder = await localAppRoot.GetFolderAsync("res");

            byte[] manifestBytes = await Disassembly.Util.ReadFile(manifestFile);

            byte[] resBytes = await Disassembly.Util.ReadFile(resFile);

            ApkReader apkReader = new ApkReader();
            ApkInfo   appinfo   = apkReader.extractInfo(manifestBytes, resBytes);

            metadata = appinfo;

            appIcon = GetAppIcon();

            //dexNet
            dexWriter = new EnhancedDexWriter();
            //dexWriter = new PlainDexWriter();
            StorageFile dexFile = await localAppRoot.GetFileAsync("classes.dex");

            byte[] dexBytes = await Disassembly.Util.ReadFile(dexFile);

            MemoryStream dexStream = new MemoryStream(dexBytes);

            dex           = new Dex(dexStream);
            dexWriter.dex = dex;

            //dexWriter.dex.GetMethod().
            var methods = dexWriter.dex.GetClasses();

            foreach (Class m in methods)
            {
                Debug.WriteLine(m.ToString());
                if (m.Name.Equals("com.example.ticom.myapp.MainActivity") || m.Name.Equals("com.example.ticom.myapp.MainActivity$1") || m.Name.StartsWith("com.example.ticom.myapp.R"))
                {
                    TextWriter tw = new StringWriter();
                    dexWriter.WriteOutClass(m, ClassDisplayOptions.Fields, tw);
                    Debug.WriteLine(tw.ToString());

                    foreach (Field f in m.GetFields())
                    {
                        Debug.WriteLine(f.ToString());
                    }

                    var meths = m.GetMethods();
                    foreach (Method x in meths)
                    {
                        //Debug.WriteLine(x.ToString());
                        Debug.WriteLine(dexWriter.WriteOutMethod(m, x, new Indentation()));
                        if (x.Name.Equals("onCreate") || x.Name.Equals("<init>"))
                        {
                            var opcodes = x.GetInstructions();
                            foreach (OpCode o in opcodes)
                            {
                                string opCodeString = o.ToString();
                                Debug.WriteLine(opCodeString);
                                if (opCodeString.Contains("meth@"))
                                {
                                    int    pos    = opCodeString.IndexOf("meth@");
                                    string methId = opCodeString.Substring(pos + 5);
                                    uint   id     = uint.Parse(methId);
                                    Method mx     = dexWriter.dex.GetMethod(id);
                                    Debug.WriteLine("meth name: " + mx.Name + "\n");
                                }
                                else if (opCodeString.Contains("type@"))
                                {
                                    int    pos    = opCodeString.IndexOf("type@");
                                    string methId = opCodeString.Substring(pos + 5);
                                    uint   id     = uint.Parse(methId);
                                    string mx     = dexWriter.dex.GetTypeName(id);
                                    Debug.WriteLine("type name: " + mx + "\n");
                                }
                                else if (opCodeString.Contains("field@"))
                                {
                                    int    pos    = opCodeString.IndexOf("field@");
                                    string methId = opCodeString.Substring(pos + 6);
                                    uint   id     = uint.Parse(methId);
                                    Field  mx     = dexWriter.dex.GetField(id);
                                    Debug.WriteLine("field info: " + mx.ToString() + "\n");
                                }
                                //Debug.WriteLine("instruction: " + o.ToString() + "\n");
                            }
                        }
                    }
                }
            }

            //context = new AstoriaContext();
        }
Example #10
0
        public static ApkInfo ReadApkFromPath(string path)
        {
            byte[] manifestData  = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }
                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                }
                            }
                        }
                    }
                }
            }

            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);

            //Console.WriteLine(string.Format("Package Name: {0}", info.packageName));
            //Console.WriteLine(string.Format("Version Name: {0}", info.versionName));
            //Console.WriteLine(string.Format("Version Code: {0}", info.versionCode));

            //Console.WriteLine(string.Format("App Has Icon: {0}", info.hasIcon));
            //if (info.iconFileName.Count > 0)
            //    Console.WriteLine(string.Format("App Icon: {0}", info.iconFileName[0]));
            //Console.WriteLine(string.Format("Min SDK Version: {0}", info.minSdkVersion));
            //Console.WriteLine(string.Format("Target SDK Version: {0}", info.targetSdkVersion));

            //if (info.Permissions != null && info.Permissions.Count > 0)
            //{
            //    Console.WriteLine("Permissions:");
            //    info.Permissions.ForEach(f =>
            //    {
            //        Console.WriteLine(string.Format("   {0}", f));
            //    });
            //}
            //else
            //    Console.WriteLine("No Permissions Found");

            //Console.WriteLine(string.Format("Supports Any Density: {0}", info.supportAnyDensity));
            //Console.WriteLine(string.Format("Supports Large Screens: {0}", info.supportLargeScreens));
            //Console.WriteLine(string.Format("Supports Normal Screens: {0}", info.supportNormalScreens));
            //Console.WriteLine(string.Format("Supports Small Screens: {0}", info.supportSmallScreens));
            return(info);
        }
        public static ApkInfo ReadApkFromPath(string path)
        {
            byte[] manifestData = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }

                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);

                                }
                            }
                        }
                    }
                }
            }

            ApkReader apkReader = new ApkReader();
            ApkInfo info = apkReader.extractInfo(manifestData, resourcesData);
            Console.WriteLine(string.Format("Package Name: {0}", info.packageName));
            Console.WriteLine(string.Format("Version Name: {0}", info.versionName));
            Console.WriteLine(string.Format("Version Code: {0}", info.versionCode));

            Console.WriteLine(string.Format("App Has Icon: {0}", info.hasIcon));
            if(info.iconFileName.Count > 0)
                Console.WriteLine(string.Format("App Icon: {0}", info.iconFileName[0]));
            Console.WriteLine(string.Format("Min SDK Version: {0}", info.minSdkVersion));
            Console.WriteLine(string.Format("Target SDK Version: {0}", info.targetSdkVersion));

            if (info.Permissions != null && info.Permissions.Count > 0)
            {
                Console.WriteLine("Permissions:");
                info.Permissions.ForEach(f =>
                {
                    Console.WriteLine(string.Format("   {0}", f));
                });
            }
            else
                Console.WriteLine("No Permissions Found");

            Console.WriteLine(string.Format("Supports Any Density: {0}", info.supportAnyDensity));
            Console.WriteLine(string.Format("Supports Large Screens: {0}", info.supportLargeScreens));
            Console.WriteLine(string.Format("Supports Normal Screens: {0}", info.supportNormalScreens));
            Console.WriteLine(string.Format("Supports Small Screens: {0}", info.supportSmallScreens));
            return info;
        }
Example #12
0
        public static ApkInfo ReadApkFromPath(string path)
        {
            byte[] manifestData  = null;
            byte[] resourcesData = null;
#if false
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }
                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                }
                            }
                        }

                        if (resourcesData != null && manifestData != null)
                        {
                            break;
                        }
                    }
                }
            }
#elif false
            var fileStream = File.OpenRead(path);
            var zipFile    = new ZipFile(fileStream);
            foreach (ZipEntry zipEntry in zipFile)
            {
                if (zipEntry.IsDirectory)
                {
                    continue;
                }
                string entryName = zipEntry.Name.ToLower();
                if (entryName == "androidmanifest.xml")
                {
                    manifestData = new byte[50 * 1024];
                    using (var stream = zipFile.GetInputStream(zipEntry))
                    {
                        stream.Read(manifestData, 0, manifestData.Length);
                    }
                }
                else if (entryName == "resources.arsc")
                {
                    using (var stream = zipFile.GetInputStream(zipEntry))
                    {
                        using (var binaryReader = new BinaryReader(stream))
                        {
                            resourcesData = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
                        }
                    }
                }
            }
#else
            using (var zipFile = ZipFile.Read(path))
            {
                foreach (var zipEntry in zipFile)
                {
                    if (zipEntry.IsDirectory)
                    {
                        continue;
                    }
                    string entryName = zipEntry.FileName.ToLower();
                    if (entryName == "androidmanifest.xml")
                    {
                        using (var stream = new MemoryStream())
                        {
                            zipEntry.Extract(stream);
                            manifestData = stream.ToArray();
                        }
                    }
                    else if (entryName == "resources.arsc")
                    {
                        using (var stream = new MemoryStream())
                        {
                            zipEntry.Extract(stream);
                            resourcesData = stream.ToArray();
                        }
                    }
                }
            }
#endif

            var apkReader = new ApkReader();
            var info      = apkReader.extractInfo(manifestData, resourcesData);
#if false
            Console.WriteLine(string.Format("Package Name: {0}", info.packageName));
            Console.WriteLine(string.Format("Version Name: {0}", info.versionName));
            Console.WriteLine(string.Format("Version Code: {0}", info.versionCode));

            Console.WriteLine(string.Format("App Has Icon: {0}", info.hasIcon));
            if (info.iconFileName.Count > 0)
            {
                Console.WriteLine(string.Format("App Icon: {0}", info.iconFileName[0]));
            }
            Console.WriteLine(string.Format("Min SDK Version: {0}", info.minSdkVersion));
            Console.WriteLine(string.Format("Target SDK Version: {0}", info.targetSdkVersion));

            if (info.Permissions != null && info.Permissions.Count > 0)
            {
                Console.WriteLine("Permissions:");
                info.Permissions.ForEach(f =>
                {
                    Console.WriteLine(string.Format("   {0}", f));
                });
            }
            else
            {
                Console.WriteLine("No Permissions Found");
            }

            Console.WriteLine(string.Format("Supports Any Density: {0}", info.supportAnyDensity));
            Console.WriteLine(string.Format("Supports Large Screens: {0}", info.supportLargeScreens));
            Console.WriteLine(string.Format("Supports Normal Screens: {0}", info.supportNormalScreens));
            Console.WriteLine(string.Format("Supports Small Screens: {0}", info.supportSmallScreens));
#endif
            return(info);
        }
Example #13
0
        public static ApkInfo ReadApkFromPath(string path)
        {
            byte[] manifestData  = null;
            byte[] resourcesData = null;

            var manifest  = "AndroidManifest.xml";
            var resources = "resources.arsc";

            //读取apk,通过解压的方式读取
            using (var zip = ZipFile.Read(path))
            {
                using (Stream zipstream = zip[manifest].OpenReader())
                {
                    //将解压出来的文件保存到一个路径(必须这样)
                    using (var fileStream = File.Create(manifest, (int)zipstream.Length))
                    {
                        manifestData = new byte[zipstream.Length];
                        zipstream.Read(manifestData, 0, manifestData.Length);
                        fileStream.Write(manifestData, 0, manifestData.Length);
                    }
                }
                using (Stream zipstream = zip[resources].OpenReader())
                {
                    //将解压出来的文件保存到一个路径(必须这样)
                    using (var fileStream = File.Create(resources, (int)zipstream.Length))
                    {
                        resourcesData = new byte[zipstream.Length];
                        zipstream.Read(resourcesData, 0, resourcesData.Length);
                        fileStream.Write(resourcesData, 0, resourcesData.Length);
                    }
                }
            }


            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);

            Console.WriteLine(string.Format("Package Name: {0}", info.packageName));
            Console.WriteLine(string.Format("Version Name: {0}", info.versionName));
            Console.WriteLine(string.Format("Version Code: {0}", info.versionCode));

            Console.WriteLine(string.Format("App Has Icon: {0}", info.hasIcon));
            if (info.iconFileName.Count > 0)
            {
                Console.WriteLine(string.Format("App Icon: {0}", info.iconFileName[0]));
            }
            Console.WriteLine(string.Format("Min SDK Version: {0}", info.minSdkVersion));
            Console.WriteLine(string.Format("Target SDK Version: {0}", info.targetSdkVersion));

            if (info.Permissions != null && info.Permissions.Count > 0)
            {
                Console.WriteLine("Permissions:");
                info.Permissions.ForEach(f =>
                {
                    Console.WriteLine(string.Format("   {0}", f));
                });
            }
            else
            {
                Console.WriteLine("No Permissions Found");
            }

            Console.WriteLine(string.Format("Supports Any Density: {0}", info.supportAnyDensity));
            Console.WriteLine(string.Format("Supports Large Screens: {0}", info.supportLargeScreens));
            Console.WriteLine(string.Format("Supports Normal Screens: {0}", info.supportNormalScreens));
            Console.WriteLine(string.Format("Supports Small Screens: {0}", info.supportSmallScreens));
            return(info);
        }
Example #14
0
        /// <summary>
        /// 解析并且保存安卓文件
        /// </summary>
        /// <returns></returns>
        private Result SaveApk(IFormFile file)
        {
            string localFile = @$ "{Directory.GetCurrentDirectory()}/temp/{DateTime.Now.Ticks}.apk";

            using (FileStream fileStream = new FileStream(localFile, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }
            string fileMD5 = FileAgent.GetMD5(localFile).Substring(0, 4);

            byte[] AndroidManifest, resources, iconData;
            try
            {
                using (ZipArchive zip = ZipFile.OpenRead(localFile))
                {
                    ZipArchiveEntry entry = zip.GetEntry("AndroidManifest.xml");
                    AndroidManifest = new byte[entry.Length];
                    entry.Open().Read(AndroidManifest, 0, AndroidManifest.Length);

                    ZipArchiveEntry ascr = zip.GetEntry("resources.arsc");
                    resources = new byte[ascr.Length];
                    ascr.Open().Read(resources, 0, resources.Length);

                    ApkReader apkReader = new ApkReader();
                    ApkInfo   info      = apkReader.extractInfo(AndroidManifest, resources);

                    string          iconFile  = info.iconFileName.Where(t => t.EndsWith(".png")).LastOrDefault();
                    ZipArchiveEntry iconEntry = zip.GetEntry(iconFile);
                    iconData = new byte[iconEntry.Length];
                    iconEntry.Open().Read(iconData, 0, iconData.Length);

                    // 上传文件至OSS
                    string version  = this.GetVersion(info.versionName);
                    string fileName = $"app/{info.label.ToPinYinAbbr().ToLower()}_{version}_{fileMD5}.apk";

                    string iconPath = $"app/{Encryption.toMD5(iconData).Substring(0, 16).ToLower()}.png";

                    string ossMessage;
                    if (!OSSAgent.Upload(_ossSetting, fileName, localFile, out ossMessage))
                    {
                        return(new Result(false, ossMessage, new
                        {
                            fileName,
                            localFile
                        }));
                    }
                    if (!OSSAgent.Upload(_ossSetting, iconPath, iconData, null, out ossMessage))
                    {
                        return(new Result(false, ossMessage));
                    }
                    string configFile = $"app/{DateTime.Now.ToString("yyyyMMHHmmss")}.json";
                    string json       = new
                    {
                        Name     = info.label,
                        File     = fileName,
                        Version  = version,
                        Icon     = iconPath,
                        Config   = configFile,
                        UpdateAt = DateTime.Now
                    }.ToJson();
                    if (!OSSAgent.Upload(_ossSetting, configFile, Encoding.UTF8.GetBytes(json), null, out ossMessage))
                    {
                        return(new Result(false, ossMessage));
                    }
                    return(new Result(true, fileName, json));
                }
            }
            catch (Exception ex)
            {
                return(new Result(false, ex.Message));
            }
            finally
            {
                File.Delete(localFile);
            }
        }
Example #15
0
 public void Test()
 {
     ApkReader.ReadMedia("001.apk");
 }
Example #16
0
        public void ReadApkFromPath(string path)
        {
            manifest = false;
            resource = false;
            byte[] manifestData  = null;
            byte[] resourcesData = null;

            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while (true)
                    {
                        if (manifest && resource)
                        {
                            break;
                        }
                        item = zip.GetNextEntry();
                        if (item != null)
                        {
                            try
                            {
                                if (item.Name.ToLower() == "androidmanifest.xml")
                                {
                                    manifestData = new byte[50 * 1024];
                                    using (Stream strm = zipfile.GetInputStream(item))
                                    {
                                        strm.Read(manifestData, 0, manifestData.Length);
                                    }
                                    manifest = true;
                                }
                                if (item.Name.ToLower() == "resources.arsc")
                                {
                                    using (Stream strm = zipfile.GetInputStream(item))
                                    {
                                        using (BinaryReader s = new BinaryReader(strm))
                                        {
                                            resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                        }
                                    }
                                    resource = true;
                                }
                            }
                            catch
                            {
                                // MessageBox.Show("err");
                            }
                        }
                    }
                }
            }

            ApkInfo info = null;

            try
            {
                ApkReader apkReader = new ApkReader();
                info = apkReader.extractInfo(manifestData, resourcesData);
            }
            catch
            {
                textBox1.AppendText("Read androidmanifest.xml Failed!" + "\n");
                return;
            }

            textBox1.AppendText(string.Format("Package Name: {0}", info.packageName) + "\n");
            PkgName.Text = info.packageName;

            textBox1.AppendText(string.Format("Name: {0}", info.label) + "\n");
            AppName.Text = info.label;
            Directory.CreateDirectory("icons");
            ExtractFileAndSave(path, info.iconFileName[0], @"icons\", info.packageName);
            if (File.Exists(@"icons\" + info.packageName + ".png"))
            {
                Image.ImageLocation = @"icons\" + info.packageName + ".png";
            }
            textBox1.AppendText(string.Format("Version Name: {0}", info.versionName) + "\n");
            textBox1.AppendText(string.Format("Version Code: {0}", info.versionCode) + "\n");
            VersionName.Text = info.versionName;
            VersionCode.Text = info.versionCode;
            textBox1.AppendText(string.Format("App Has Icon: {0}", info.hasIcon) + "\n");
            if (info.iconFileName.Count > 0)
            {
                Console.WriteLine(string.Format("App Icon: {0}", info.iconFileName[0]) + "\n");
            }
            textBox1.AppendText(string.Format("Min SDK Version: {0}", info.minSdkVersion) + "\n");
            textBox1.AppendText(string.Format("Target SDK Version: {0}", info.targetSdkVersion) + "\n");

            if (info.Permissions != null && info.Permissions.Count > 0)
            {
                textBox1.AppendText("Permissions:" + "\n");
                info.Permissions.ForEach(f =>
                {
                    textBox1.AppendText(string.Format("   {0}", f) + "\n");
                });
            }
            else
            {
                textBox1.AppendText("No Permissions Found" + "\n");
            }
            textBox1.AppendText(string.Format("Supports Any Density: {0}", info.supportAnyDensity) + "\n");
            textBox1.AppendText(string.Format("Supports Large Screens: {0}", info.supportLargeScreens) + "\n");
            textBox1.AppendText(string.Format("Supports Normal Screens: {0}", info.supportNormalScreens) + "\n");
            textBox1.AppendText(string.Format("Supports Small Screens: {0}", info.supportSmallScreens) + "\n");
            return;
        }