|
| 1 | +# Copyright 2026 B.Kats and Tom Rothamel <pytom@bishoujo.us> |
| 2 | +# |
| 3 | +# Permission is hereby granted, free of charge, to any person |
| 4 | +# obtaining a copy of this software and associated documentation files |
| 5 | +# (the "Software"), to deal in the Software without restriction, |
| 6 | +# including without limitation the rights to use, copy, modify, merge, |
| 7 | +# publish, distribute, sublicense, and/or sell copies of the Software, |
| 8 | +# and to permit persons to whom the Software is furnished to do so, |
| 9 | +# subject to the following conditions: |
| 10 | +# |
| 11 | +# The above copyright notice and this permission notice shall be |
| 12 | +# included in all copies or substantial portions of the Software. |
| 13 | +# |
| 14 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 15 | +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 16 | +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 17 | +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
| 18 | +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 19 | +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 20 | +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 21 | + |
| 22 | + |
| 23 | +######################################## |
| 24 | +## WARNING for when editing this file ## |
| 25 | +######################################## |
| 26 | + |
| 27 | +# This file contain functions that need to support async handling for the web build |
| 28 | +# Renaming or reordering any functions will break the async handling |
| 29 | +# The cython generated names for the following functions need to be listed |
| 30 | +# in the ASYNCIFY_ONLY list: (tasks/renpython.py; 2 names for each function) |
| 31 | +# - generate_private_key |
| 32 | +# - sign_data |
| 33 | +# - verify_data |
| 34 | +# - get_public_key_from_private |
| 35 | +# - validate_private_key |
| 36 | +# - validate_public_key |
| 37 | + |
| 38 | +from libc.stdlib cimport free |
| 39 | +import base64 |
| 40 | + |
| 41 | +cdef extern from "ec_sign_core.h": |
| 42 | + int ECSign(const unsigned char *priv_key_der, size_t key_len, const char *data, size_t data_len, char *signature, size_t signature_len); |
| 43 | + int ECVerify(const unsigned char *public_key_der, size_t key_len, const char *data, size_t data_len, char *signature, size_t signature_len); |
| 44 | + |
| 45 | + void ECGeneratePrivateKey(unsigned char **priv_key_der, size_t *priv_len); |
| 46 | + void ECGetPublicKeyFromPrivate(const unsigned char *priv_key_der, size_t priv_len, unsigned char **public_key_der, size_t *pub_len); |
| 47 | + |
| 48 | + int ECValidateKey(int public, const unsigned char *key_der, size_t key_len); |
| 49 | + |
| 50 | +def generate_private_key() -> bytes | None: |
| 51 | + cdef unsigned char* privkey = NULL |
| 52 | + cdef size_t privlen = 0 |
| 53 | + |
| 54 | + ECGeneratePrivateKey(&privkey, &privlen) |
| 55 | + |
| 56 | + rv = None |
| 57 | + if privlen > 0 and privkey != NULL: |
| 58 | + rv = bytes(privkey[:privlen]) |
| 59 | + |
| 60 | + free(privkey); |
| 61 | + |
| 62 | + return rv |
| 63 | + |
| 64 | +def sign_data(data : bytes, private_key : bytes) -> bytes: |
| 65 | + sign = bytes(64) |
| 66 | + |
| 67 | + if not ECSign(private_key, len(private_key), data, len(data), sign, len(sign)): |
| 68 | + raise Exception("Failed to sign data"); |
| 69 | + |
| 70 | + # print(" ".join("{:02x}".format(x) for x in sign)) |
| 71 | + return sign |
| 72 | + |
| 73 | +def verify_data(data : bytes, public_key : bytes, sign : bytes) -> bool: |
| 74 | + # print(" ".join("{:02x}".format(x) for x in sign)) |
| 75 | + return ECVerify(public_key, len(public_key), data, len(data), sign, len(sign)) |
| 76 | + |
| 77 | +def get_public_key_from_private(private_key : bytes) -> bytes | None: |
| 78 | + cdef unsigned char* pubkey = NULL |
| 79 | + cdef size_t publen = 0 |
| 80 | + |
| 81 | + ECGetPublicKeyFromPrivate(private_key, len(private_key), &pubkey, &publen) |
| 82 | + |
| 83 | + rv = None |
| 84 | + if publen > 0 and pubkey != NULL: |
| 85 | + rv = bytes(pubkey[:publen]) |
| 86 | + |
| 87 | + free(pubkey) |
| 88 | + |
| 89 | + return rv |
| 90 | + |
| 91 | +def validate_private_key(private_key : bytes) -> bool: |
| 92 | + return ECValidateKey(0, private_key, len(private_key)) |
| 93 | + |
| 94 | +def validate_public_key(public_key : bytes) -> bool: |
| 95 | + return ECValidateKey(1, public_key, len(public_key)) |
| 96 | + |
| 97 | +def _pem_lines(contents: bytes) -> typing.Iterator[bytes]: |
| 98 | + in_pem_part = False |
| 99 | + seen_pem_start = False |
| 100 | + |
| 101 | + for line in contents.splitlines(): |
| 102 | + line = line.strip() |
| 103 | + |
| 104 | + # Skip empty lines |
| 105 | + if not line: |
| 106 | + continue |
| 107 | + |
| 108 | + # Handle start marker |
| 109 | + if line.startswith(b'-----BEGIN'): |
| 110 | + if in_pem_part: |
| 111 | + raise ValueError('Seen start marker twice') |
| 112 | + |
| 113 | + in_pem_part = True |
| 114 | + seen_pem_start = True |
| 115 | + continue |
| 116 | + |
| 117 | + # Skip stuff before first marker |
| 118 | + if not in_pem_part: |
| 119 | + continue |
| 120 | + |
| 121 | + # Handle end marker |
| 122 | + if in_pem_part and line.startswith(b'-----END'): |
| 123 | + in_pem_part = False |
| 124 | + break |
| 125 | + |
| 126 | + # Load fields |
| 127 | + if b":" in line: |
| 128 | + continue |
| 129 | + |
| 130 | + yield line |
| 131 | + |
| 132 | + # Do some sanity checks |
| 133 | + if not seen_pem_start: |
| 134 | + raise ValueError('No PEM start marker found') |
| 135 | + |
| 136 | + if in_pem_part: |
| 137 | + raise ValueError('No PEM end marker found') |
| 138 | + |
| 139 | +def pem_to_der(pem : bytes | str) -> bytes: |
| 140 | + if isinstance(pem, str): # pragma: no branch |
| 141 | + pem = pem.encode() |
| 142 | + |
| 143 | + d = b"".join(_pem_lines(pem)) |
| 144 | + return base64.b64decode(d) |
| 145 | + |
| 146 | + |
| 147 | +def der_to_pem(der : bytes, name : str) -> bytes: |
| 148 | + b64 = base64.b64encode(der) |
| 149 | + lines = [("-----BEGIN %s KEY-----\n" % name).encode()] |
| 150 | + lines.extend( |
| 151 | + [b64[start : start + 76] + b"\n" for start in range(0, len(b64), 76)] |
| 152 | + ) |
| 153 | + lines.append(("-----END %s KEY-----\n" % name).encode()) |
| 154 | + return b"".join(lines) |
0 commit comments