Files
PunchLog/src/punchlog/msa.py
T

119 lines
4.1 KiB
Python

"""MSA (ZTE) encryption envelope, reverse-engineered from cn.com.zte.android.util.KmsKeyUtil.
Scheme summary (fully reproduced in pure Python):
- A per-exchange AES-256 key ``localKeyString``: 32 random uppercase ASCII letters
(A-Z), then base64-encoded. The 32 ASCII bytes ARE the AES key; the base64 text is
what gets passed around as ``dataKeyPlain``.
- Request body: ``AES/GCM/NoPadding`` (12-byte IV, 128-bit tag). Output text is
``base64(ciphertext+tag) + "$$" + base64(iv)``.
- ``X-MSA-Encrypt-DataKey`` header = RSA-OAEP(SHA-256) encrypt of ``localKeyString``
using the server's transmission public key (X509 DER, base64).
- ``X-MSA-Encrypt-PublicKey`` header = the client's freshly generated RSA public key
(X509 DER, base64). The server encrypts its response AES key to this key.
- Response body is decrypted by: RSA-OAEP-decrypt the response ``X-MSA-Encrypt-DataKey``
header with the client private key to recover the server's ``localKeyString``, then
AES-GCM-decrypt the body with it.
RSA: 2048-bit, OAEP with SHA-256 and MGF1(SHA-256). Encrypt chunk size 245, decrypt 256.
"""
from __future__ import annotations
import base64
import os
import secrets
import string
from dataclasses import dataclass
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
_OAEP = padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
)
RSA_ENC_CHUNK = 245
RSA_DEC_CHUNK = 256
SPLIT_FLAG = "$$"
def _b64e(b: bytes) -> str:
return base64.b64encode(b).decode("ascii")
def _b64d(s: str) -> bytes:
return base64.b64decode(s)
def gen_local_key_string() -> str:
"""32 random uppercase A-Z chars, base64-encoded (KmsKeyUtil.getLocalKeyString)."""
raw = "".join(secrets.choice(string.ascii_uppercase) for _ in range(32))
return _b64e(raw.encode("ascii"))
@dataclass
class RSAKeyPair:
public_b64: str # X509 SubjectPublicKeyInfo DER, base64
private_b64: str # PKCS8 DER, base64
_priv: rsa.RSAPrivateKey
@classmethod
def generate(cls) -> "RSAKeyPair":
priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pub_der = priv.public_key().public_bytes(
serialization.Encoding.DER,
serialization.PublicFormat.SubjectPublicKeyInfo,
)
priv_der = priv.private_bytes(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
return cls(_b64e(pub_der), _b64e(priv_der), priv)
def load_public_from_b64(pub_b64: str):
return serialization.load_der_public_key(_b64d(pub_b64))
def encrypt_rsa(server_pub_b64: str, plaintext: str) -> str:
"""RSA-OAEP(SHA-256) encrypt, chunked by 245 bytes, concatenated, base64."""
pub = load_public_from_b64(server_pub_b64)
data = plaintext.encode("utf-8")
out = bytearray()
for i in range(0, len(data), RSA_ENC_CHUNK):
out += pub.encrypt(data[i:i + RSA_ENC_CHUNK], _OAEP)
return _b64e(bytes(out))
def decrypt_rsa_bytes(priv: rsa.RSAPrivateKey, encrypted_b64: str) -> bytes:
data = _b64d(encrypted_b64)
out = bytearray()
for i in range(0, len(data), RSA_DEC_CHUNK):
out += priv.decrypt(data[i:i + RSA_DEC_CHUNK], _OAEP)
return bytes(out)
def decrypt_rsa(priv: rsa.RSAPrivateKey, encrypted_b64: str) -> str:
return decrypt_rsa_bytes(priv, encrypted_b64).decode("utf-8")
def encrypt_aes_gcm(plaintext: str, local_key_string: str) -> str:
key = _b64d(local_key_string) # 32 bytes
iv = os.urandom(12)
ct = AESGCM(key).encrypt(iv, plaintext.encode("utf-8"), None) # ct||tag
return _b64e(ct) + SPLIT_FLAG + _b64e(iv)
def decrypt_aes_gcm(encrypted_text: str, data_key_plain: str) -> str:
parts = encrypted_text.split(SPLIT_FLAG)
if len(parts) != 2:
raise ValueError("Invalid encrypted text format")
ct = _b64d(parts[0])
iv = _b64d(parts[1])
key = _b64d(data_key_plain)
return AESGCM(key).decrypt(iv, ct, None).decode("utf-8")