Files
jeb-utils/src/jeb_utils/crypto_utils.py
T

49 lines
1.6 KiB
Python

# Copyright 2026 jCloud Services GbR
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
__all__ = [
'generate_keypair',
'serialize_public_key',
'deserialize_public_key',
'derive_aes_key'
]
def generate_keypair():
private_key = ec.generate_private_key(ec.SECP256R1())
return private_key, private_key.public_key()
def serialize_public_key(public_key: ec.EllipticCurvePublicKey) -> bytes:
return public_key.public_bytes(
encoding=serialization.Encoding.X962,
format=serialization.PublicFormat.UncompressedPoint,
)
def deserialize_public_key(data: bytes) -> ec.EllipticCurvePublicKey:
return ec.EllipticCurvePublicKey.from_encoded_point(
ec.SECP256R1(), data
)
def derive_aes_key(private_key, peer_public_key) -> bytes:
shared_secret = private_key.exchange(ec.ECDH(), peer_public_key)
return HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'handshake',
).derive(shared_secret)