介绍一下Android中签名用的Key的产生方法。

产生Key
工具: openssl


1 产生RSA私钥(private key)
openssl genrsa -3 -out testkey.pem 2048
解释:
-3 是算法的参数 2048 是私钥长度,testkey.pem 是输出的文件。

2 产生PKCS#10格式的认证请求。
openssl req -new -x509 -key testkey.pem -out testkey.x509.pem -days 10000 -config c:\openssl\bin\openssl.cnf
后面的配置文件位置请根据自己的安装openssl目录确定,如果执行文件openssl目录下可以不用写路径
 

openssl会提示你输入相关信息,这里的信息可以根据你自己的实际情况填写。如:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [GB]:CN
State or Province Name (full name) [Berkshire]:GuangDong
Locality Name (eg, city) [Newbury]:ShenZhen
Organization Name (eg, company) [My Company Ltd]:XXXX
Organizational Unit Name (eg, section) []:XXX

Common Name (eg, your name or your server’s hostname) []:XXX.com
Email Address []:[email protected]

3 把私钥的格式转换成PKCS #8(Private-Key Information Syntax Standard.)

openssl pkcs8 -in testkey.pem -topk8 -outform DER -out testkey.pk8 -nocrypt

这里指定了-nocryp,表示不加密。


签名

Android提供了为jar/zip文件签名的程序signapk.jar 。

它的用法如下:
Usage: signapk publickey.x509[.pem] privatekey.pk8 input.jar output.jar

EX:   java -jar signapk.jar testkey.x509.pem testkey.pk8 update.zip update-signed.zip

用解压缩工具打开Update-signed.zip  在目录META-INF可以看到

 

Android Rom签名文件的生成与签名_第1张图片

现在我们来看看签名到底做了些什么:

o 先为输入的jar/zip文件中的所有文件生成SHA1数字签名(除了CERT.RSA,CERT.SF和MANIFEST.MF)

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);
}
}
并把数字签名信息写入MANIFEST.MF

je = new JarEntry(JarFile.MANIFEST_NAME);
je.setTime(timestamp);
outputJar.putNextEntry(je);
manifest.write(outputJar);

对manifest签名并写入CERT.SF

// 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。

// CERT.RSA
je = new JarEntry(CERT_RSA_NAME);
je.setTime(timestamp);
outputJar.putNextEntry(je);
writeSignatureBlock(signature, publicKey, outputJar);