summaryrefslogtreecommitdiff
path: root/scripts/keygeneration/create_new_android_keys.sh
blob: ce8253d11f01ed8336ae7c8f54fe9afd96a7761b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/bin/bash

# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Load common constants and functions.
. "$(dirname "$0")/common.sh"

usage() {
  cat <<EOF
Usage: ${PROG} [FLAGS] DIR

Generate Android's 4 framework key pairs at DIR.  For detail, please refer to
"Certificates and private keys" and "Manually generating keys" in
https://source.android.com/devices/tech/ota/sign_builds.html.

FLAGS:
  --rotate-from  Directory containing a set of old key pairs to rotate from
EOF

  if [[ $# -ne 0 ]]; then
    die "$*"
  else
    exit 0
  fi
}

# Use the same SUBJECT used in Nexus.
SUBJECT='/C=US/ST=California/L=Mountain View/O=Google Inc./OU=Android/CN=Android'

# Generate .pk8 and .x509.pem at the given directory.
make_pair() {
  local dir=$1
  local name=$2

  # Generate RSA key.
  openssl genrsa -3 -out "${dir}/temp.pem" 2048

  # Create a certificate with the public part of the key.
  openssl req -new -x509 -key "${dir}/temp.pem" -out "${dir}/${name}.x509.pem" \
    -days 10000 -subj "${SUBJECT}"

  # Create a PKCS#8-formatted version of the private key.
  openssl pkcs8 -in "${dir}/temp.pem" -topk8 -outform DER \
    -out "${dir}/${name}.pk8" -nocrypt

  # Best attempt to securely delete the temp.pem file.
  shred --remove "${dir}/temp.pem"
}

main() {
  set -e

  local dir
  local old_dir

  while [[ $# -gt 0 ]]; do
    case $1 in
    -h|--help)
      usage
      ;;
    --rotate-from)
      old_dir="$2"
      shift 2
      ;;
    -*)
      usage "Unknown option: $1"
      ;;
    *)
      break
      ;;
    esac
  done

  if [[ $# -ne 1 ]]; then
    usage "Missing output directory"
  fi
  dir=$1

  for name in platform shared media releasekey; do
    make_pair "${dir}" "${name}"

    if [ -d "${old_dir}" ]; then
      apksigner rotate --out "${dir}/${name}.lineage" \
        --old-signer --key "${old_dir}/${name}.pk8" \
            --cert "${old_dir}/${name}.x509.pem" \
        --new-signer --key "${dir}/${name}.pk8" --cert "${dir}/${name}.x509.pem"
    fi
  done
}

main "$@"