Android签名机制
Android的签名机制是为了保证 apk 的完整性
keystore
keystore 是一个文件,它用一个密码保护,通过 keytool 命令打开 keystore 文件需要输入密码
// 查看证书,my_key.keystore是keystore的路径,my_pass 是keystore的密码
keytool -list -v -keystore my_key.keystore -storepass my_pass
// 导出证书,my_key_1是别名,my_new.crt 是要导出的到的文件的名字,my_key.keystore是 keystore 的路径
keytool -export -alias my_key_1 -file my_new.crt -keystore my_key.keystore
数字签名和数字证书
数字摘要:对不同长度的数据通过算法得到一个固定的长度输入,常用的算法有MD5、SHA1、SHA256
数字签名:使用私钥对数字摘要进行签名。(非对称密钥:公钥加密,私钥解密;私钥签名,公钥验签)
数字证书:CA(Certificate Authority)用自己的私钥对申请人的公钥和一些基本信息做签名,然后把申请人的公钥、基本信息和数字签名放到一起组成的一个证书。而CA本身也会生成一个证书,是自签名的,也叫根证书,会内置在操作系统里面。
给定一个 apk 文件解压,可以看到一个 META-INFO 文件夹,在该文件下有三个文件:MANIFEST.MF、CERT.SF 和 CERT.RSA,说明 apk 已经签名了。
如何生成未签名的apk
- 在 app/bulid.gradle 中注释掉 bulidTypes/release 中的签名配置
- 执行命令 ./gradlew assembleRelease
给未签名的 apk 签名
jarsigner -verbose -keystore my_key.keystore -signedjar result_singed.apk app-release-unsigned.apk my_key_1
- my_key.keystore keystore文件的路径
- app-release-unsigned.apk 输入的未签名文件路径
- my_key_1 keystore里面的一个alias
MANIFEST.MF
摘要文件,对 apk 中所有的文件,逐个用 Hash 算法(SHA1/SHA256)生成摘要信息,再用 Base64 进行编码后写入文件中,如果改变了 apk 包中的文件,在安装校验时就会失败。
CERT.SF
对摘要的签名文件,对前一步生成的 MANIFEST.MF 文件进行 Hash 计算,还对 MANIFEST.MF 中的每一条内容也进行 Hash 计算,将 Hash 结果进行 Base64 编码后写入文件中。MANIFEST.MF 和 CERT.SF 做的都是摘要。
CERT.RSA
保存了公钥、所采用的加密算法等信息,此外还保存了对 CERT.SF 中的内容用私钥加签的值。如果攻击者修改了 apk 中的某个文件,并生成了新的摘要文件,但是攻击者没有开发者的私钥,就不能生成了正常的签名。
keytool -printcert file CERT.RSA // 查看证书所有者等信息
X.509证书格式
版本号
证书序列号
–
算法|参数 (签名算法标志,CA对证书进行签名用的算法,一般是SHA1withRSA,即先对证书做Hash,然后对Hash值做签名)
–
发行者名称
生效日期|终止日期
主体名称
算法|参数|密钥(主体公钥信息:包含开发者的加密算法及密钥信息(RSA、公钥))
–
算法|参数|已加密的Hash值(签名,用CA的私钥对证书的所有域及对这些域的Hash值一起签名)
可以通过 openssl pkcs7 -inform DER -in CERT.RSA -noout -print_certs -text 将 CERT.RSA证书中的内容答应出来。
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 1005375368 (0x3beccf88)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, O=Android, CN=Android Debug
Validity
Not Before: Dec 29 10:10:49 2014 GMT
Not After : Dec 21 10:10:49 2044 GMT
Subject: C=US, O=Android, CN=Android Debug
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:d8:b9:a8:66:5f:09:b0:04:86:3f:23:9e:c2:84:
93:a0:e3:dc:a2:5f:d3:ab:48:29:e9:e6:33:16:69:
56:87:4f:34:41:ce:be:3e:d0:a4:fa:33:27:e7:79:
7d:d3:0b:63:22:d3:27:f9:7b:f2:23:30:23:13:39:
24:4c:92:f2:15:60:35:ed:91:87:77:86:e7:f0:df:
2d:93:fd:59:26:86:93:4e:e5:13:e2:bf:55:5a:6a:
e7:3d:ac:48:50:10:d4:96:71:2d:c7:f9:df:91:0b:
b8:b0:0f:8d:b9:f2:8f:ec:65:33:c6:6c:a9:79:b1:
da:74:d1:0f:cc:7a:c3:ed:d1:a2:85:42:86:ae:88:
2a:dd:3c:8b:b0:d5:e5:45:07:42:a0:96:65:b4:ac:
2f:98:7e:8a:36:2f:b8:0d:a7:1c:0f:38:f1:56:9c:
13:f6:3c:a0:2c:f7:a9:e8:cb:17:95:44:4f:dc:e2:
ce:b7:9e:a3:f8:c2:fa:71:c0:f0:20:76:29:34:34:
d9:e0:18:12:f9:ec:40:a9:2a:f1:39:cd:30:43:da:
de:92:71:92:88:fd:28:0a:17:b7:cd:c8:d8:fb:45:
ca:1c:61:bc:13:91:2e:01:b2:20:36:1b:18:b8:aa:
e0:95:e0:ab:98:fa:9c:1b:6b:7f:bd:27:66:ab:5e:
d0:9b
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
A5:02:31:28:2E:76:1B:10:11:68:AD:32:5C:8F:DC:00:30:80:BB:7C
Signature Algorithm: sha256WithRSAEncryption
ba:0d:dc:9a:f9:12:97:12:b0:7c:d6:07:e7:bd:27:32:46:60:
75:4b:e3:b4:3e:09:f7:90:53:cd:4d:f5:bf:61:3f:2a:2e:2f:
d0:c8:50:c2:3b:29:62:10:25:7d:6b:53:48:88:e1:76:60:33:
52:45:ac:df:5f:49:95:ee:ac:75:81:14:46:2f:e0:26:30:be:
d8:5d:2b:1c:a2:2f:30:34:c9:f4:9c:e4:c4:86:54:71:69:3d:
de:2d:97:fe:dc:68:9f:13:d0:b9:86:e8:24:b9:75:04:cf:db:
1d:cf:d0:36:db:06:b9:87:37:3c:89:25:02:12:8b:fc:42:9e:
5e:18:69:25:5f:2a:52:ab:5a:a1:19:f6:3f:3b:9c:d3:5d:bd:
ce:0b:5d:a0:f9:d6:0b:de:05:ff:89:24:b3:ad:9b:4e:5c:9f:
07:c2:b2:d9:55:44:49:e7:b7:cf:a2:ca:68:ae:64:0d:8a:56:
43:9b:de:ad:e5:d6:d5:86:76:ba:34:d4:90:e8:0a:ba:26:73:
8c:4b:7d:8c:92:02:bb:62:2c:9b:83:e8:d3:2f:74:01:72:89:
b4:a2:08:12:c3:64:90:40:b2:8e:60:fd:db:6b:08:a7:db:32:
98:f7:7a:ce:c9:78:46:42:7d:09:31:6a:5f:b8:81:87:2f:62:
1e:e2:d3:7d
签名源码:SignApk(android2.2)
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.signapk;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
import sun.security.pkcs.SignerInfo;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X500Name;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.AlgorithmParameters;
import java.security.DigestOutputStream;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
* Command line tool to sign JAR files (including APKs and OTA updates) in
* a way compatible with the mincrypt verifier, using SHA1 and RSA keys.
*/
class SignApk {
private static final String CERT_SF_NAME = "META-INF/CERT.SF";
private static final String CERT_RSA_NAME = "META-INF/CERT.RSA";
// Files matching this pattern are not copied to the output.
private static Pattern stripPattern =
Pattern.compile("^META-INF/(.*)[.](SF|RSA|DSA)$");
private static X509Certificate readPublicKey(File file)
throws IOException, GeneralSecurityException {
FileInputStream input = new FileInputStream(file);
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(input);
} finally {
input.close();
}
}
/**
* Reads the password from stdin and returns it as a string.
*
* @param keyFile The file containing the private key. Used to prompt the user.
*/
private static String readPassword(File keyFile) {
// TODO: use Console.readPassword() when it's available.
System.out.print("Enter password for " + keyFile + " (password will not be hidden): ");
System.out.flush();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
try {
return stdin.readLine();
} catch (IOException ex) {
return null;
}
}
/**
* Decrypt an encrypted PKCS 8 format private key.
*
* Based on ghstark's post on Aug 6, 2006 at
* http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949
*
* @param encryptedPrivateKey The raw data of the private key
* @param keyFile The file containing the private key
*/
private static KeySpec decryptPrivateKey(byte[] encryptedPrivateKey, File keyFile)
throws GeneralSecurityException {
EncryptedPrivateKeyInfo epkInfo;
try {
epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
} catch (IOException ex) {
// Probably not an encrypted key.
return null;
}
char[] password = readPassword(keyFile).toCharArray();
SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
Key key = skFactory.generateSecret(new PBEKeySpec(password));
Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());
try {
return epkInfo.getKeySpec(cipher);
} catch (InvalidKeySpecException ex) {
System.err.println("signapk: Password for " + keyFile + " may be bad.");
throw ex;
}
}
/** Read a PKCS 8 format private key. */
private static PrivateKey readPrivateKey(File file)
throws IOException, GeneralSecurityException {
DataInputStream input = new DataInputStream(new FileInputStream(file));
try {
byte[] bytes = new byte[(int) file.length()];
input.read(bytes);
KeySpec spec = decryptPrivateKey(bytes, file);
if (spec == null) {
spec = new PKCS8EncodedKeySpec(bytes);
}
try {
return KeyFactory.getInstance("RSA").generatePrivate(spec);
} catch (InvalidKeySpecException ex) {
return KeyFactory.getInstance("DSA").generatePrivate(spec);
}
} finally {
input.close();
}
}
/** Add the SHA1 of every file to the manifest, creating it if necessary. */
private static Manifest addDigestsToManifest(JarFile jar)
throws IOException, GeneralSecurityException {
Manifest input = jar.getManifest();
Manifest output = new Manifest();
Attributes main = output.getMainAttributes();
if (input != null) {
main.putAll(input.getMainAttributes());
} else {
main.putValue("Manifest-Version", "1.0");
main.putValue("Created-By", "1.0 (Android SignApk)");
}
BASE64Encoder base64 = new BASE64Encoder();
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] buffer = new byte[4096];
int num;
// We sort the input entries by name, and add them to the
// output manifest in sorted order. We expect that the output
// map will be deterministic.
TreeMap<String, JarEntry> byName = new TreeMap<String, JarEntry>();
for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) {
JarEntry entry = e.nextElement();
byName.put(entry.getName(), entry);
}
for (JarEntry entry: byName.values()) {
String name = entry.getName();
if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) &&
!name.equals(CERT_SF_NAME) && !name.equals(CERT_RSA_NAME) &&
(stripPattern == null ||
!stripPattern.matcher(name).matches())) {
InputStream data = jar.getInputStream(entry);
while ((num = data.read(buffer)) > 0) {
md.update(buffer, 0, num);
}
Attributes attr = null;
if (input != null) attr = input.getAttributes(name);
attr = attr != null ? new Attributes(attr) : new Attributes();
attr.putValue("SHA1-Digest", base64.encode(md.digest()));
output.getEntries().put(name, attr);
}
}
return output;
}
/** Write to another stream and also feed it to the Signature object. */
private static class SignatureOutputStream extends FilterOutputStream {
private Signature mSignature;
public SignatureOutputStream(OutputStream out, Signature sig) {
super(out);
mSignature = sig;
}
@Override
public void write(int b) throws IOException {
try {
mSignature.update((byte) b);
} catch (SignatureException e) {
throw new IOException("SignatureException: " + e);
}
super.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
mSignature.update(b, off, len);
} catch (SignatureException e) {
throw new IOException("SignatureException: " + e);
}
super.write(b, off, len);
}
}
/** Write a .SF file with a digest the specified manifest. */
private static void writeSignatureFile(Manifest manifest, OutputStream out)
throws IOException, GeneralSecurityException {
Manifest sf = new Manifest();
Attributes main = sf.getMainAttributes();
main.putValue("Signature-Version", "1.0");
main.putValue("Created-By", "1.0 (Android SignApk)");
BASE64Encoder base64 = new BASE64Encoder();
MessageDigest md = MessageDigest.getInstance("SHA1");
PrintStream print = new PrintStream(
new DigestOutputStream(new ByteArrayOutputStream(), md),
true, "UTF-8");
// Digest of the entire manifest
manifest.write(print);
print.flush();
main.putValue("SHA1-Digest-Manifest", base64.encode(md.digest()));
Map<String, Attributes> entries = manifest.getEntries();
for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
// Digest of the manifest stanza for this entry.
print.print("Name: " + entry.getKey() + "\r\n");
for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
print.print(att.getKey() + ": " + att.getValue() + "\r\n");
}
print.print("\r\n");
print.flush();
Attributes sfAttr = new Attributes();
sfAttr.putValue("SHA1-Digest", base64.encode(md.digest()));
sf.getEntries().put(entry.getKey(), sfAttr);
}
sf.write(out);
}
/** Write a .RSA file with a digital signature. */
private static void writeSignatureBlock(
Signature signature, X509Certificate publicKey, OutputStream out)
throws IOException, GeneralSecurityException {
SignerInfo signerInfo = new SignerInfo(
new X500Name(publicKey.getIssuerX500Principal().getName()),
publicKey.getSerialNumber(),
AlgorithmId.get("SHA1"),
AlgorithmId.get("RSA"),
signature.sign());
PKCS7 pkcs7 = new PKCS7(
new AlgorithmId[] { AlgorithmId.get("SHA1") },
new ContentInfo(ContentInfo.DATA_OID, null),
new X509Certificate[] { publicKey },
new SignerInfo[] { signerInfo });
pkcs7.encodeSignedData(out);
}
/**
* Copy all the files in a manifest from input to output. We set
* the modification times in the output to a fixed time, so as to
* reduce variation in the output file and make incremental OTAs
* more efficient.
*/
private static void copyFiles(Manifest manifest,
JarFile in, JarOutputStream out, long timestamp) throws IOException {
byte[] buffer = new byte[4096];
int num;
Map<String, Attributes> entries = manifest.getEntries();
List<String> names = new ArrayList(entries.keySet());
Collections.sort(names);
for (String name : names) {
JarEntry inEntry = in.getJarEntry(name);
JarEntry outEntry = null;
if (inEntry.getMethod() == JarEntry.STORED) {
// Preserve the STORED method of the input entry.
outEntry = new JarEntry(inEntry);
} else {
// Create a new entry so that the compressed len is recomputed.
outEntry = new JarEntry(name);
}
outEntry.setTime(timestamp);
out.putNextEntry(outEntry);
InputStream data = in.getInputStream(inEntry);
while ((num = data.read(buffer)) > 0) {
out.write(buffer, 0, num);
}
out.flush();
}
}
public static void main(String[] args) {
if (args.length != 4) {
System.err.println("Usage: signapk " +
"publickey.x509[.pem] privatekey.pk8 " +
"input.jar output.jar");
System.exit(2);
}
JarFile inputJar = null;
JarOutputStream outputJar = null;
try {
X509Certificate publicKey = readPublicKey(new File(args[0]));
// Assume the certificate is valid for at least an hour.
long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;
PrivateKey privateKey = readPrivateKey(new File(args[1]));
inputJar = new JarFile(new File(args[2]), false); // Don't verify.
outputJar = new JarOutputStream(new FileOutputStream(args[3]));
outputJar.setLevel(9);
JarEntry je;
// MANIFEST.MF
Manifest manifest = addDigestsToManifest(inputJar);
je = new JarEntry(JarFile.MANIFEST_NAME);
je.setTime(timestamp);
outputJar.putNextEntry(je);
manifest.write(outputJar);
// CERT.SF
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
je = new JarEntry(CERT_SF_NAME);
je.setTime(timestamp);
outputJar.putNextEntry(je);
writeSignatureFile(manifest,
new SignatureOutputStream(outputJar, signature));
// CERT.RSA
je = new JarEntry(CERT_RSA_NAME);
je.setTime(timestamp);
outputJar.putNextEntry(je);
writeSignatureBlock(signature, publicKey, outputJar);
// Everything else
copyFiles(manifest, inputJar, outputJar, timestamp);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
try {
if (inputJar != null) inputJar.close();
if (outputJar != null) outputJar.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
}