转载时请注明出处和作者联系方式
文章出处:http://www.limodev.cn/blog
作者联系方式:李先静

昨天看了一下Android中的签名机制,这里介绍一下Android中签名用的Key的产生方法和签名的原理。

产生Key

o 产生RSA私钥(private key)
openssl genrsa -3 -out testkey.pem 2048

-3 是算法的参数(public exponent)。
2048 是私钥长度。
testkey.pem 是输出的文件。

o 产生PKCS#10格式的认证请求。所谓认证请求就是发给认证机构认证的一个请求,它主要包括一个公钥和一些相关信息(如组织名称和联系人邮件地址)。
openssl req -new -x509 -key testkey.pem -out testkey.x509.pem -days 10000 /
-subj ‘/C=US/ST=California/L=Mountain View/O=Android/OU=Android/CN=Android/[email protected]

如果不提供最后两个参数,openssl会提示你输入相关信息,这里的信息可以根据你自己的实际情况填写。如:

openssl req -new -x509 -key testkey.pem -out testkey.x509.pem -days 10000

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]:Topwise
Organizational Unit Name (eg, section) []:Broncho
Common Name (eg, your name or your server’s hostname) []:broncho.cn
Email Address []:[email protected]

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

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

私钥是不能让别人知道的,否则就起不到保密的作用了。私钥通常是要加密保存的,但这里指定了-nocryp,表示不加密。

Android提供了一个脚本mkkey.sh用来简化上面的步骤:

if ["$1" == ""]; then
   echo "Create a test certificate key."
   echo "Usage: $0 NAME"
   echo "Will generate NAME.pk8 and NAME.x509.pem"
   echo "  /C=US/ST=California/L=Mountain View/O=Android/OU=Android/CN=Android/[email protected]"
   return
fi

openssl genrsa -3 -out $1.pem 2048

openssl req -new -x509 -key $1.pem -out $1.x509.pem -days 10000 /
   -subj '/C=US/ST=California/L=Mountain View/O=Android/OU=Android/CN=Android/[email protected]'

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