建立非對稱式金鑰組

本指南說明如何為 Media CDN 建立非對稱金鑰組。

產生金鑰

指令列

您可以使用 Python 3 和 OpenSSL 1.1.1 以上版本 (舊版 OpenSSL 不支援 Ed25519) 產生私密金鑰和公開金鑰。

  1. 產生私密金鑰。

    openssl genpkey -algorithm ed25519 -outform PEM -out test.private.key
    

    這會輸出 PEM 編碼的私密金鑰。請妥善保管這組金鑰,建議您使用金鑰管理系統或 Secret Manager

  2. 使用 URL 安全 Base64 格式,從私密金鑰產生公開金鑰。

    openssl pkey -outform DER -pubout -in test.private.key | tail -c +13 | python3 -c "import base64, sys; print(('%s' % base64.urlsafe_b64encode(sys.stdin.buffer.read()))[2:-1])"
    

    這個指令會從私密金鑰產生公開金鑰,並從原始公開金鑰中移除 ASN.1 標頭資訊。

Python

import base64

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519


def generate_ed25519_keypair(
    private_key_filename: str = "private.key", public_key_filename: str = "public.pub"
) -> None:
    """Generate Ed25519 Keys Pairs.

    Args:
        private_key_filename(default private.key): private key filename as a string.
        public_key_filename(default public.pub): public key filename as a string

    Returns:

    """
    private_key = ed25519.Ed25519PrivateKey.generate()
    public_key = private_key.public_key()

    private_key_str = private_key.private_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PrivateFormat.Raw,
        encryption_algorithm=serialization.NoEncryption(),
    )
    print("Private Key:\t", base64.urlsafe_b64encode(private_key_str))

    public_key_str = public_key.public_bytes(
        encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw
    )
    print("Public Key:\t", base64.urlsafe_b64encode(public_key_str))

    with open(private_key_filename, "wb") as fp:
        fp.write(base64.urlsafe_b64encode(private_key_str))
        print(f"Private Key is written to:\t{private_key_filename}")

    with open(public_key_filename, "wb") as fp:
        fp.write(base64.urlsafe_b64encode(public_key_str))
        print(f"Public Key is written to:\t{public_key_filename}")

有了這個格式的金鑰,您現在可以將金鑰加入金鑰組。當金鑰組以 cdnPolicy.signedRequestKeyset 的形式與路由建立關聯時,Media CDN 會在提供任何內容前驗證要求是否已簽署。