File size: 2,266 Bytes
b8989d2
d1b70e9
 
 
 
bb410e4
d1b70e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb410e4
 
d1b70e9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# agents/tools/identity.py

import uuid
import json
import base64
from datetime import datetime, UTC

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

DEFAULT_KEY_TYPE = "ed25519"  # Можно поменять на "rsa" при необходимости


def generate_did():
    """Генерация уникального DiD на основе UUID v4"""
    return f"did:hmp:{uuid.uuid4()}"


def generate_keys(key_type=DEFAULT_KEY_TYPE):
    """Генерация пары ключей"""
    if key_type == "rsa":
        private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    elif key_type == "ed25519":
        private_key = ed25519.Ed25519PrivateKey.generate()
    else:
        raise ValueError(f"Неизвестный тип ключа: {key_type}")

    public_key = private_key.public_key()
    return private_key, public_key


def serialize_private_key(private_key, password=None):
    """Сериализация приватного ключа"""
    encryption = (
        serialization.BestAvailableEncryption(password.encode())
        if password else
        serialization.NoEncryption()
    )
    return private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=encryption,
    ).decode()


def serialize_public_key(public_key):
    """Сериализация публичного ключа"""
    return public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    ).decode()


def create_identity(name="Core Identity", key_type=DEFAULT_KEY_TYPE, metadata=None, password=None):
    """Создание полной идентичности"""
    did = generate_did()
    priv_key, pub_key = generate_keys(key_type)

    identity = {
        "id": did,
        "name": name,
        "pubkey": serialize_public_key(pub_key),
        "privkey": serialize_private_key(priv_key, password),
        "metadata": json.dumps(metadata or {}),
        "created_at": datetime.now(UTC).isoformat(),
        "updated_at": datetime.now(UTC).isoformat(),
    }
    return identity