From 000768391165c3ae105a01b57204e7c2f6e18c0a Mon Sep 17 00:00:00 2001 From: Sergey Matveev Date: Thu, 17 Mar 2022 12:38:53 +0300 Subject: [PATCH] Ability to reuse the key for reissuing --- pygost/asn1schemas/cert-selfsigned-example.py | 55 +++++++++++++------ 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/pygost/asn1schemas/cert-selfsigned-example.py b/pygost/asn1schemas/cert-selfsigned-example.py index 6887696..ae1ee00 100755 --- a/pygost/asn1schemas/cert-selfsigned-example.py +++ b/pygost/asn1schemas/cert-selfsigned-example.py @@ -102,10 +102,19 @@ parser.add_argument( "--issue-with", help="Path to PEM with CA to issue the child", ) +parser.add_argument( + "--reuse-key", + help="Path to PEM with the key to reuse", +) parser.add_argument( "--out-key", help="Path to PEM with the resulting key", ) +parser.add_argument( + "--only-key", + action="store_true", + help="Only generate the key", +) parser.add_argument( "--out-cert", help="Path to PEM with the resulting certificate", @@ -199,29 +208,41 @@ if args.issue_with is not None: if params["publicKeyParamSet"] == curve_oid ])) +key_params = GostR34102012PublicKeyParameters(( + ("publicKeyParamSet", ai["publicKeyParamSet"]), +)) + def pem(obj): return fill(standard_b64encode(obj.encode()).decode("ascii"), 64) -key_params = GostR34102012PublicKeyParameters(( - ("publicKeyParamSet", ai["publicKeyParamSet"]), -)) - -prv_raw = urandom(ai["prv_len"]) -out = stdout if args.out_key is None else open(args.out_key, "w") -print("-----BEGIN PRIVATE KEY-----", file=out) -print(pem(PrivateKeyInfo(( - ("version", Integer(0)), - ("privateKeyAlgorithm", PrivateKeyAlgorithmIdentifier(( - ("algorithm", ai["key_algorithm"]), - ("parameters", Any(key_params)), - ))), - ("privateKey", PrivateKey(OctetString(prv_raw).encode())), -))), file=out) -print("-----END PRIVATE KEY-----", file=out) +if args.reuse_key is not None: + with open(args.reuse_key, "rb") as fd: + lines = fd.read().decode("ascii").split("-----") + idx = lines.index("BEGIN PRIVATE KEY") + if idx == -1: + raise ValueError("PEM has no PRIVATE KEY") + prv_raw = standard_b64decode(lines[idx + 1]) + pki = PrivateKeyInfo().decod(prv_raw) + prv = prv_unmarshal(bytes(OctetString().decod(bytes(pki["privateKey"])))) +else: + prv_raw = urandom(ai["prv_len"]) + out = stdout if args.out_key is None else open(args.out_key, "w") + print("-----BEGIN PRIVATE KEY-----", file=out) + print(pem(PrivateKeyInfo(( + ("version", Integer(0)), + ("privateKeyAlgorithm", PrivateKeyAlgorithmIdentifier(( + ("algorithm", ai["key_algorithm"]), + ("parameters", Any(key_params)), + ))), + ("privateKey", PrivateKey(OctetString(prv_raw).encode())), + ))), file=out) + print("-----END PRIVATE KEY-----", file=out) + if args.only_key: + exit() + prv = prv_unmarshal(prv_raw) -prv = prv_unmarshal(prv_raw) curve = ai["curve"] pub_raw = pub_marshal(public_key(curve, prv)) rdn = [RelativeDistinguishedName(( -- 2.44.0