Android Rom簽名文件的生成與簽名

介紹一下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可以看到

 

現在我們來看看簽名到底做了些什麼:

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);

 

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