Android keys - release keys

Android default keys are located at build/target/product/security/, ROM providers must use OEM keys when building factory images for market products.
There are 5 paris of keys in all: (*.pk8 is private key, *.x509.pem is cert)

testkey (I call it dev key)
shared
platform
media
verity

1. How to specify OEM keys

config release key location in .mk, example:

PRODUCT_DEFAULT_DEV_CERTIFICATE := /home/xx/release_keys/releasekey
PRODUCT_OTA_PUBLIC_KEYS=/home/xx/release_keys/otakey.x509.pem

Then system will search for $(PRODUCT_DEFAULT_DEV_CERTIFICATE).pk8 and $(PRODUCT_DEFAULT_DEV_CERTIFICATE).x509.pem for release key.

$(PRODUCT_OTA_PUBLIC_KEYS) will generate target file META/otakeys.txt with content: “/home/xx/release_keys/otakey.x509.pem”

2. What are the keys used for

2.1 release key

If release key is not specified, it will default to build/target/product/security/testkey
This key will be used to:

- sign normal apk
- The cert will be save to /system/etc/security/otacerts.zip, which will be used to verify OTA pkg signature
- sign OTA pkg

2.2 shared/media/platform keys

These keys will be put into the same folder as PRODUCT_DEFAULT_DEV_CERTIFICATE
These keys will be used to:

- sign specific apk

For example:

LOCAL_CERTIFICATE := shared    eg.: Launcher, Dialer, etc.
LOCAL_CERTIFICATE := platform  eg.: Settings, Nfc, TelephonyProvider, CertInstaller, etc
LOCAL_CERTIFICATE := media     eg.: DownloadProvider,MediaProvider, Gallery etc.

2.3 verity key

In Android Lollipop, verity key is set to build/target/product/security/verity.{pk8,x509.pem} in build/target/product/verity.mk. OEM vendors need to define PRODUCT_VERITY_SIGNING_KEY by themselves.
verity key will be used to:

- sign boot.img, 
  the signature will be verified by bootloader.
  OEM vendors should build verity pub key inside bootloader, or put the pub key in some other secure storage.
- sign verity metadata in system.img,
  the signature will be verified by boot.img,
  boot.img has the pub key /verity_key in ramdisk.

3. Resign flow of Android

Build signing guide from google: https://source.android.com/devices/tech/ota/sign_builds.html

Typical re-signing flow: sign boot.img/system.img with verity_key, sign apks with specified keys, manually change META/otacerts.zip if needed.

./build/tools/releasetools/sign_target_files_apks \
    --replace_ota_keys \
    --default_key_mappings /home/xx/release_keys/  \
    --replace_verity_public_key=/home/xx/release_keys/verity_key \
    --replace_verity_private_key=/home/xx/release_keys/verity \
    orig.zip signed-target.zip

Typical OTA package generation: sign with new ota key

./build/tools/releasetools/ota_from_target_files \
    -k ~/release_keys/otakey \
    signed-target.zip \
    signed-ota_update.zip

‘ota_from_target_files’ needs some scripts in <android_src>/build and some host tools under <android_src>/out/host/linxu-x86, like “SignApk.jar”, “imgdiff” and needed shared libraries.