Skip to content

Utils

convert_der_to_rsv(signature, v_adjustment_factor=0)

Convert DER signature to RSV format.

Parameters:

Name Type Description Default
signature bytes

The DER-encoded signature bytes

required
v_adjustment_factor int

The v value adjustment factor for the signature

0

Returns:

Name Type Description
SignatureComponents dict

A dictionary containing the r, s, and v components

Raises:

Type Description
ValueError

If the signature is invalid or cannot be decoded

Source code in web3_google_hsm/utils.py
def convert_der_to_rsv(signature: bytes, v_adjustment_factor: int = 0) -> dict:
    """
    Convert DER signature to RSV format.

    Args:
        signature: The DER-encoded signature bytes
        v_adjustment_factor: The v value adjustment factor for the signature

    Returns:
        SignatureComponents: A dictionary containing the r, s, and v components

    Raises:
        ValueError: If the signature is invalid or cannot be decoded
    """
    r, s = ecdsa.util.sigdecode_der(signature, ecdsa.SECP256k1.order)
    v = v_adjustment_factor
    if s > SECP256_K1_N / 2:
        s = SECP256_K1_N - s
    r = r.to_bytes(32, byteorder="big")
    s = s.to_bytes(32, byteorder="big")
    return {"v": v, "r": r, "s": s}

extract_public_key_bytes(pem_str)

Extract raw public key bytes from PEM format.

Parameters:

Name Type Description Default
pem_str str

PEM-encoded public key string

required

Returns:

Name Type Description
bytes bytes

Raw public key bytes (64 bytes of X,Y coordinates)

Raises:

Type Description
ValueError

If the PEM string is invalid

Source code in web3_google_hsm/utils.py
def extract_public_key_bytes(pem_str: str) -> bytes:
    """
    Extract raw public key bytes from PEM format.

    Args:
        pem_str: PEM-encoded public key string

    Returns:
        bytes: Raw public key bytes (64 bytes of X,Y coordinates)

    Raises:
        ValueError: If the PEM string is invalid
    """
    if not pem_str.startswith("-----BEGIN PUBLIC KEY-----"):
        pem_str = f"-----BEGIN PUBLIC KEY-----\n{pem_str}\n-----END PUBLIC KEY-----"

    try:
        pem_bytes = pem_str.encode()
        public_key = serialization.load_pem_public_key(pem_bytes)

        raw_bytes = public_key.public_bytes(
            encoding=serialization.Encoding.X962, format=serialization.PublicFormat.UncompressedPoint
        )
        return raw_bytes[-64:]
    except Exception as err:
        msg = "Invalid PEM format"
        raise ValueError(msg) from err