在代码中对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。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值