#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.


cat << EOF > rootca.cnf
[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name
prompt = no
string_mask = utf8only
x509_extensions = extensions

[ req_distinguished_name ]
C = CN
O = Test
CN = Test Enterprise Root CA

[ extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer
basicConstraints = CA:TRUE
keyUsage = cRLSign, keyCertSign
EOF

# generate private ca key
openssl genpkey -algorithm rsa-pss -pkeyopt rsa_keygen_pubexp:65537 -pkeyopt rsa_keygen_bits:4096 -out rootca_pri.pem
# generate public root key, default to 10 years
openssl req -x509 -sha256 -days 3650 -new -key rootca_pri.pem -config rootca.cnf -sha256 -out rootca.pem

# create a strong and random password, eg: openssl rand -hex 32
# encrypt rootca
openssl pkcs12 -export -in rootca.pem -inkey rootca_pri.pem -out rootca.pfx
# transform to der format
openssl x509 -inform pem  -in rootca.pem  -outform der -out rootca.der
rm -f rootca_pri.pem rootca.cnf
