在代碼中對apk文件重簽名

廢話不說,上代碼:

public static boolean signApk(String sourcePath, String targetPath, String key,
			String passwd, String alias) {
		if (sourcePath == null || targetPath == null || passwd == null|| key == null)
			return false;

		File file = new File(sourcePath);
		if (!file.exists())
			return false;
		
		file=new File(key);
		if(!file.exists())
			return false;		

		String cmd = "jarsigner -verbose -keystore " + key + " -signedjar " + targetPath + " " + sourcePath + " " + alias;
		Process process=null;		
		try {
			process = Runtime.getRuntime().exec(cmd);
			OutputStream outputStream = process.getOutputStream();
			outputStream.write(passwd.getBytes());
			outputStream.close();
			InputStream inputStream = process.getInputStream();
			InputStreamReader reader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(reader);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				System.out.println(line);
				if(line.contains("incorrect"))
					return false;
			}
			bufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

sourcePath是要簽名的apk路徑,targetPath是簽名後生成的文件路徑,key爲使用的keystore路徑,passwd爲keystore對應的密碼,alias是keystore的別名。

如果不知道怎麼獲取alias,可以使用下面的代碼,alias可以在工程根目錄下的alias.txt中查看:

public static void getAlias(String key, String passwd){
		String cmd = "cmd.exe /c keytool -list -v -keystore "+key+" -storepass "+passwd+" > ./alias.txt";
		try {
			Process process=null;
			process= Runtime.getRuntime().exec(cmd);
			if (process != null) {
				InputStream inputStream = process.getErrorStream();
				InputStreamReader reader = new InputStreamReader(inputStream);
				BufferedReader bufferedReader = new BufferedReader(reader);
				String line = null;
				while ((line = bufferedReader.readLine()) != null) {
					System.out.println(line);
				}
				bufferedReader.close();
				reader.close();
				inputStream.close();
				process.destroy();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

其中keytool同樣是JDK下的工具,這裏直接使用了,所以也需要實現配置好JAVA_HOME。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章