Beispiel #1
0
    def PassFactor(passphrase: str,
                   owner_entropy: bytes,
                   has_lot_seq: bool) -> bytes:
        """
        Compute the passfactor as specified in BIP38 (with EC multiplication).

        Args:
            passphrase (str)     : Passphrase
            owner_entropy (bytes): Owner entropy
            has_lot_seq (bool)   : True if lot and sequence numbers are present, false otherwise

        Returns:
            bytes: Passfactor
        """

        # Compute the prefactor
        prefactor = CryptoUtils.Scrypt(StringUtils.NormalizeNfc(passphrase),
                                       _Bip38EcUtils.OwnerSaltFromEntropy(owner_entropy, has_lot_seq),
                                       key_len=Bip38EcConst.SCRYPT_PREFACTOR_KEY_LEN,
                                       n=Bip38EcConst.SCRYPT_PREFACTOR_N,
                                       r=Bip38EcConst.SCRYPT_PREFACTOR_P,
                                       p=Bip38EcConst.SCRYPT_PREFACTOR_R)
        # Compute the passfactor
        if has_lot_seq:
            passfactor = CryptoUtils.DoubleSha256(prefactor + owner_entropy)
        else:
            passfactor = prefactor

        return passfactor
Beispiel #2
0
    def TaggedHash(tag: Union[bytes, str],
                   data_bytes: bytes) -> bytes:
        """
        Implementation of the hash tag function as defined by BIP-0340.
        Tagged hash = SHA256(SHA256(tag) || SHA256(tag) || data)

        Args:
            tag (bytes or str): Tag, if bytes it'll be considered already hashed
            data_bytes (bytes): Data bytes

        Returns:
            bytes: Tagged hash
        """
        tag_hash = CryptoUtils.Sha256(tag) if isinstance(tag, str) else tag
        return CryptoUtils.Sha256(tag_hash + tag_hash + data_bytes)
Beispiel #3
0
    def EncodeKey(pub_key: Union[bytes, IPublicKey], **kwargs: Any) -> str:
        """
        Encode a public key to Bitcoin Cash P2PKH address.

        Args:
            pub_key (bytes or IPublicKey): Public key bytes or object

        Other Parameters:
            hrp (str)      : HRP
            net_ver (bytes): Net address version

        Returns:
            str: Address string

        Raises:
            ValueError: If the public key is not valid
            TypeError: If the public key is not secp256k1
        """
        hrp = kwargs["hrp"]
        net_ver_bytes = kwargs["net_ver"]

        pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)
        return BchBech32Encoder.Encode(
            hrp, net_ver_bytes,
            CryptoUtils.Hash160(pub_key_obj.RawCompressed().ToBytes()))
Beispiel #4
0
    def DecodeAddr(addr: str, **kwargs: Any) -> bytes:
        """
        Decode a P2PKH address to bytes.

        Args:
            addr (str): Address string

        Other Parameters:
            net_ver (bytes)                        : Net address version
            base58_alph (Base58Alphabets, optional): Base58 alphabet, Bitcoin alphabet by default

        Returns:
            bytes: Public key hash bytes

        Raises:
            ValueError: If the address encoding is not valid
        """
        net_ver_bytes = kwargs["net_ver"]
        base58_alph = kwargs.get("base58_alph", Base58Alphabets.BITCOIN)

        try:
            addr_dec_bytes = Base58Decoder.CheckDecode(addr, base58_alph)
        except Base58ChecksumError as ex:
            raise ValueError("Invalid base58 checksum") from ex
        else:
            # Validate length
            AddrDecUtils.ValidateLength(
                addr_dec_bytes,
                CryptoUtils.Hash160DigestSize() + len(net_ver_bytes))
            # Validate and remove prefix
            return AddrDecUtils.ValidateAndRemovePrefix(
                addr_dec_bytes, net_ver_bytes)
Beispiel #5
0
    def EncodeKey(pub_key: Union[bytes, IPublicKey], **kwargs: Any) -> str:
        """
        Encode a public key to P2PKH address.

        Args:
            pub_key (bytes or IPublicKey): Public key bytes or object

        Other Parameters:
            net_ver (bytes)                        : Net address version
            base58_alph (Base58Alphabets, optional): Base58 alphabet, Bitcoin alphabet by default

        Returns:
            str: Address string

        Raises:
            ValueError: If the public key is not valid
            TypeError: If the public key is not secp256k1
        """
        net_ver_bytes = kwargs["net_ver"]
        base58_alph = kwargs.get("base58_alph", Base58Alphabets.BITCOIN)
        pub_key_mode = kwargs.get("pub_key_mode", P2PKHPubKeyModes.COMPRESSED)

        pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)
        pub_key_bytes = (pub_key_obj.RawCompressed().ToBytes()
                         if pub_key_mode == P2PKHPubKeyModes.COMPRESSED else
                         pub_key_obj.RawUncompressed().ToBytes())

        return Base58Encoder.CheckEncode(
            net_ver_bytes + CryptoUtils.Hash160(pub_key_bytes), base58_alph)
Beispiel #6
0
    def EncodeKeyBytes(pub_key_bytes: bytes, addr_type: FillAddrTypes) -> str:
        """
        Encode a public key to Filecoin address.

        Args:
            pub_key_bytes (bytes)    : Public key bytes
            addr_type (FillAddrTypes): Address type

        Returns:
            str: Address string
        """

        # Get address type
        addr_type_str = chr(addr_type + ord("0"))

        # Compute public key hash and checksum
        pub_key_hash_bytes = CryptoUtils.Blake2b(
            pub_key_bytes, digest_size=FilAddrConst.BLAKE2B_BYTE_LEN)
        checksum_bytes = _FilAddrUtils.ComputeChecksum(pub_key_hash_bytes,
                                                       addr_type)
        # Encode to base32
        b32_enc = Base32Encoder.EncodeNoPadding(
            pub_key_hash_bytes + checksum_bytes, FilAddrConst.BASE32_ALPHABET)

        return CoinsConf.Filecoin.Params(
            "addr_prefix") + addr_type_str + b32_enc
Beispiel #7
0
    def _FromSeed(cls, seed_bytes: bytes,
                  key_net_ver: Bip32KeyNetVersions) -> Bip32Base:
        """
        Create a Bip32 object from the specified seed (e.g. BIP39 seed).

        Args:
            seed_bytes (bytes)                      : Seed bytes
            key_net_ver (Bip32KeyNetVersions object): Bip32KeyNetVersions object

        Returns:
            Bip32Base object: Bip32Base object

        Raises:
            ValueError: If the seed is too short
            Bip32KeyError: If the seed is not suitable for master key generation
        """

        # Compute kL and kR
        kl_bytes, kr_bytes = cls._HashRepeatedly(seed_bytes)
        # Tweak kL bytes
        kl_bytes = cls._TweakMasterKeyBits(kl_bytes)

        # Compute chain code
        chain_code_bytes = CryptoUtils.HmacSha256(cls._MasterKeyHmacKey(),
                                                  b"\x01" + seed_bytes)
        # Compute private key
        priv_key = Ed25519KholawPrivateKey.FromBytes(kl_bytes + kr_bytes)

        return cls(priv_key=priv_key,
                   pub_key=None,
                   key_data=Bip32KeyData(chain_code=chain_code_bytes),
                   curve_type=cls.CurveType(),
                   key_net_ver=key_net_ver)
Beispiel #8
0
    def DecodeAddr(addr: str, **kwargs: Any) -> bytes:
        """
        Decode an Algorand address to bytes.

        Args:
            addr (str): Address string

        Other Parameters:
            hrp (str): HRP

        Returns:
            bytes: Public key hash bytes

        Raises:
            ValueError: If the address encoding is not valid
        """
        hrp = kwargs["hrp"]

        try:
            addr_dec_bytes = Bech32Decoder.Decode(hrp, addr)
        except Bech32ChecksumError as ex:
            raise ValueError("Invalid bech32 checksum") from ex
        else:
            AddrDecUtils.ValidateLength(addr_dec_bytes,
                                        CryptoUtils.Hash160DigestSize())
            return addr_dec_bytes
Beispiel #9
0
    def DeriveKeyHalves(passpoint: bytes,
                        address_hash: bytes,
                        owner_entropy: bytes) -> Tuple[bytes, bytes]:
        """
        Compute the scrypt as specified in BIP38 (without EC multiplication)and derive the two key halves.

        Args:
            passpoint (bytes)    : Passpoint
            address_hash (bytes) : Address hash
            owner_entropy (bytes): Owner entropy

        Returns:
            tuple[bytes, bytes]: Derived key halves
        """

        # Derive a key from passpoint, address hash and owner entropy
        key = CryptoUtils.Scrypt(passpoint,
                                 address_hash + owner_entropy,
                                 key_len=Bip38EcConst.SCRYPT_HALVES_KEY_LEN,
                                 n=Bip38EcConst.SCRYPT_HALVES_N,
                                 r=Bip38EcConst.SCRYPT_HALVES_R,
                                 p=Bip38EcConst.SCRYPT_HALVES_P)
        # Split the resulting 64 bytes in half
        derived_half_1 = key[:Bip38EcConst.SCRYPT_HALVES_KEY_LEN // 2]
        derived_half_2 = key[Bip38EcConst.SCRYPT_HALVES_KEY_LEN // 2:]

        return derived_half_1, derived_half_2
Beispiel #10
0
    def EncodeKey(pub_key: Union[bytes, IPublicKey], **kwargs: Any) -> str:
        """
        Encode a public key to Ethereum address.

        Args:
            pub_key (bytes or IPublicKey): Public key bytes or object

        Other Parameters:
            skip_chksum_enc (bool, optional): True to skip checksum encoding, false otherwise (default)

        Returns:
            str: Address string

        Raised:
            ValueError: If the public key is not valid
            TypeError: If the public key is not secp256k1
        """
        skip_chksum_enc = kwargs.get("skip_chksum_enc", False)

        pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)

        # First byte of the uncompressed key (i.e. 0x04) is not needed
        kekkak_hex = BytesUtils.ToHexString(
            CryptoUtils.Kekkak256(pub_key_obj.RawUncompressed().ToBytes()[1:]))
        addr = kekkak_hex[EthAddrConst.START_BYTE:]
        return CoinsConf.Ethereum.Params("addr_prefix") + (
            _EthAddrUtils.ChecksumEncode(addr)
            if not skip_chksum_enc else addr)
Beispiel #11
0
    def GeneratePrivateKey(int_passphrase: str,
                           pub_key_mode: Bip38PubKeyModes) -> str:
        """
        Generate a random encrypted private key from the intermediate passphrase.

        Args:
            int_passphrase (str)           : Intermediate passphrase
            pub_key_mode (Bip38PubKeyModes): Public key mode

        Returns:
            str: Encrypted private key

        Raises:
            Base58ChecksumError: If base58 checksum is not valid
            ValueError: If the intermediate code is not valid
        """

        # Decode intermediate passphrase
        int_passphrase_bytes = Base58Decoder.CheckDecode(int_passphrase)

        # Check length
        if len(int_passphrase_bytes) != Bip38EcConst.INT_PASS_ENC_BYTE_LEN:
            raise ValueError(f"Invalid intermediate code length ({len(int_passphrase_bytes)})")

        # Get all the parts back
        magic = int_passphrase_bytes[:8]
        owner_entropy = int_passphrase_bytes[8:16]
        passpoint = Secp256k1PublicKey.FromBytes(int_passphrase_bytes[16:])

        # Check magic
        if magic not in (Bip38EcConst.INT_PASS_MAGIC_NO_LOT_SEQ, Bip38EcConst.INT_PASS_MAGIC_WITH_LOT_SEQ):
            raise ValueError(f"Invalid magic ({BytesUtils.ToHexString(magic)})")

        # Generate seedb
        seedb = os.urandom(Bip38EcConst.SEED_B_BYTE_LEN)
        # Compute factorb from seedb
        factorb = CryptoUtils.DoubleSha256(seedb)

        # Compute address hash
        address_hash = Bip38Addr.AddressHash(
            Secp256k1PublicKey.FromPoint(passpoint.Point() * BytesUtils.ToInteger(factorb)),
            pub_key_mode
        )
        # Derive key halves from the passpoint, address hash and owner entropy
        derived_half_1, derived_half_2 = _Bip38EcUtils.DeriveKeyHalves(passpoint.RawCompressed().ToBytes(),
                                                                       address_hash,
                                                                       owner_entropy)
        # Encrypt seedb in two parts
        encrypted_part_1, encrypted_part_2 = Bip38EcKeysGenerator.__EncryptSeedb(seedb,
                                                                                 derived_half_1,
                                                                                 derived_half_2)

        # Get flagbyte by setting bits
        flagbyte = Bip38EcKeysGenerator.__SetFlagbyteBits(magic, pub_key_mode)
        # Concatenate all parts
        enc_key_bytes = (Bip38EcConst.ENC_KEY_PREFIX + flagbyte + address_hash
                         + owner_entropy + encrypted_part_1[:8] + encrypted_part_2)

        # Encode in Base58Check
        return Base58Encoder.CheckEncode(enc_key_bytes)
Beispiel #12
0
    def DeriveKeyHalves(passphrase: str,
                        address_hash: bytes) -> Tuple[bytes, bytes]:
        """
        Compute the scrypt as specified in BIP38 (without EC multiplication) and derive the two key halves.

        Args:
            passphrase (str)    : Passphrase
            address_hash (bytes): Address hash

        Returns:
            tuple[bytes, bytes]: Derived key halves
        """

        # Derive a key from passphrase and address hash
        key = CryptoUtils.Scrypt(StringUtils.NormalizeNfc(passphrase),
                                 address_hash,
                                 key_len=Bip38NoEcConst.SCRYPT_KEY_LEN,
                                 n=Bip38NoEcConst.SCRYPT_N,
                                 r=Bip38NoEcConst.SCRYPT_R,
                                 p=Bip38NoEcConst.SCRYPT_P)
        # Split the resulting 64 bytes in half
        derived_half_1 = key[:Bip38NoEcConst.SCRYPT_KEY_LEN // 2]
        derived_half_2 = key[Bip38NoEcConst.SCRYPT_KEY_LEN // 2:]

        return derived_half_1, derived_half_2
Beispiel #13
0
    def __DecryptAndGetFactorb(encrypted_part_1_lower: bytes,
                               encrypted_part_2: bytes,
                               derived_half_1: bytes,
                               derived_half_2: bytes) -> bytes:
        """
        Decrypt and get back factorb.

        Args:
            encrypted_part_1_lower (bytes): Lower part of first encrypted part
            encrypted_part_2 (bytes)      : Second encrypted part
            derived_half_1 (bytes)        : First half of derived key
            derived_half_2 (bytes)        : Second half of derived key

        Returns:
            bytes: Factorb
        """

        # Use derived_half_2 as AES key
        aes_dec = AesEcbDecrypter(derived_half_2)
        aes_dec.AutoUnPad(False)

        # Decrypt the second part and get back the higher parts of seedb and encrypted half 1
        decrypted_part_2 = BytesUtils.Xor(aes_dec.Decrypt(encrypted_part_2), derived_half_1[16:])
        encrypted_part_1_higher = decrypted_part_2[:8]
        seedb_part_2 = decrypted_part_2[8:]

        # Decrypt the first part to get the lower part of seedb
        seedb_part_1 = BytesUtils.Xor(aes_dec.Decrypt(encrypted_part_1_lower + encrypted_part_1_higher),
                                      derived_half_1[:16])
        # Rebuild the complete seedb
        seedb = seedb_part_1 + seedb_part_2

        # Compute factorb from seedb
        return CryptoUtils.DoubleSha256(seedb)
Beispiel #14
0
    def EncodeKey(pub_key: Union[bytes, IPublicKey], **kwargs: Any) -> str:
        """
        Encode a public key to Tezos address.

        Args:
            pub_key (bytes or IPublicKey): Public key bytes or object

        Other Parameters:
            prefix (XtzAddrPrefixes): Address prefix

        Returns:
            str: Address string

        Raises:
            ValueError: If the public key is not valid
            TypeError: If the public key is not ed25519 or the prefix is not a XtzAddrPrefixes enum
        """

        # Get and check prefix
        prefix = kwargs["prefix"]
        if not isinstance(prefix, XtzAddrPrefixes):
            raise TypeError(
                "Address type is not an enumerative of XtzAddrPrefixes")

        # Get public key
        pub_key_obj = AddrKeyValidator.ValidateAndGetEd25519Key(pub_key)

        # Compute Blake2b and encode in base58 with checksum
        blake_bytes = CryptoUtils.Blake2b(
            pub_key_obj.RawCompressed().ToBytes()[1:],
            digest_size=XtzAddrConst.BLAKE2B_BYTE_LEN)

        return Base58Encoder.CheckEncode(prefix.value + blake_bytes)
Beispiel #15
0
    def EncodeKey(pub_key: Union[bytes, IPublicKey], **kwargs: Any) -> str:
        """
        Encode a public key to Neo address.

        Args:
            pub_key (bytes or IPublicKey): Public key bytes or object

        Other Parameters:
            ver (bytes): Version

        Returns:
            str: Address string

        Raises:
            ValueError: If the public key is not valid
            TypeError: If the public key is not ed25519
        """
        ver_bytes = kwargs["ver"]

        pub_key_obj = AddrKeyValidator.ValidateAndGetNist256p1Key(pub_key)

        # Get payload
        payload_bytes = (NeoAddrConst.PREFIX +
                         pub_key_obj.RawCompressed().ToBytes() +
                         NeoAddrConst.SUFFIX)
        # Encode to base58
        return Base58Encoder.CheckEncode(ver_bytes +
                                         CryptoUtils.Hash160(payload_bytes))
Beispiel #16
0
    def DecodeAddr(addr: str, **kwargs: Any) -> bytes:
        """
        Decode a Bitcoin Cash P2PKH address to bytes.

        Args:
            addr (str): Address string

        Other Parameters:
            hrp (str)      : HRP
            net_ver (bytes): Net address version

        Returns:
            bytes: Public key hash bytes

        Raises:
            ValueError: If the address encoding is not valid
        """
        hrp = kwargs["hrp"]
        net_ver_bytes = kwargs["net_ver"]

        try:
            net_ver_bytes_got, addr_dec_bytes = BchBech32Decoder.Decode(
                hrp, addr)
        except Bech32ChecksumError as ex:
            raise ValueError("Invalid bech32 checksum") from ex
        else:
            # Check net version
            if net_ver_bytes != net_ver_bytes_got:
                raise ValueError(
                    f"Invalid net version (expected {BytesUtils.ToHexString(net_ver_bytes)}, "
                    f"got {BytesUtils.ToHexString(net_ver_bytes_got)})")
            # Validate length
            AddrDecUtils.ValidateLength(addr_dec_bytes,
                                        CryptoUtils.Hash160DigestSize())
            return addr_dec_bytes
Beispiel #17
0
    def KeyIdentifier(self) -> bytes:
        """
        Get key identifier.

        Returns:
            bytes: Key identifier bytes
        """
        return CryptoUtils.Hash160(self.m_pub_key.RawCompressed().ToBytes())
Beispiel #18
0
    def AddScriptSig(pub_key: IPublicKey) -> bytes:
        """
        Add script signature to public key and get address bytes.

        Args:
            pub_key (IPublicKey object): Public key object

        Returns:
            bytes: Address bytes
        """

        # Key hash: Hash160(public_key)
        key_hash_bytes = CryptoUtils.Hash160(pub_key.RawCompressed().ToBytes())
        # Script signature: 0x0014 | Hash160(public_key)
        script_sig_bytes = P2SHAddrConst.SCRIPT_BYTES + key_hash_bytes
        # Address bytes = Hash160(script_signature)
        return CryptoUtils.Hash160(script_sig_bytes)
    def Encode(self, entropy_bytes: bytes) -> Mnemonic:
        """
        Encode bytes to mnemonic phrase.

        Args:
            entropy_bytes (bytes): Entropy bytes (accepted lengths in bits: 128, 160, 192, 224, 256)

        Returns:
            Mnemonic object: Encoded mnemonic

        Raises:
            ValueError: If entropy is not valid
        """

        # Check entropy length
        entropy_byte_len = len(entropy_bytes)
        if not Bip39EntropyGenerator.IsValidEntropyByteLen(entropy_byte_len):
            raise ValueError(
                f"Entropy byte length ({entropy_byte_len}) is not valid")

        # Convert entropy to binary string
        entropy_bin_str = BytesUtils.ToBinaryStr(entropy_bytes,
                                                 entropy_byte_len * 8)
        # Get entropy hash as binary string
        entropy_hash_bin_str = BytesUtils.ToBinaryStr(
            CryptoUtils.Sha256(entropy_bytes),
            CryptoUtils.Sha256DigestSize() * 8)
        # Get mnemonic binary string by concatenating entropy and checksum
        mnemonic_bin_str = entropy_bin_str + entropy_hash_bin_str[:entropy_byte_len
                                                                  // 4]

        # Get mnemonic from entropy
        mnemonic = []
        for i in range(
                len(mnemonic_bin_str) // Bip39MnemonicConst.WORD_BIT_LEN):
            # Get current word index
            word_bin_str = (
                mnemonic_bin_str[i * Bip39MnemonicConst.WORD_BIT_LEN:(i + 1) *
                                 Bip39MnemonicConst.WORD_BIT_LEN])
            word_idx = IntegerUtils.FromBinaryStr(word_bin_str)
            # Get word at given index
            mnemonic.append(self.m_words_list.GetWordAtIdx(word_idx))

        return Bip39Mnemonic.FromList(mnemonic)
Beispiel #20
0
    def ComputeChecksum(payload_bytes: bytes) -> bytes:
        """
        Compute checksum in Stellar format.

        Args:
            payload_bytes (bytes): Payload bytes

        Returns:
            bytes: Computed checksum
        """
        return BytesUtils.Reverse(CryptoUtils.XModemCrc(payload_bytes))
Beispiel #21
0
    def __ComputeChecksumBinaryStr(self, mnemonic_bin_str: str) -> str:
        """
        Compute checksum from mnemonic binary string.

        Args:
            mnemonic_bin_str (str): Mnemonic binary string

        Returns:
           str: Computed checksum binary string
        """

        # Get entropy bytes
        entropy_bytes = self.__EntropyBytesFromBinaryStr(mnemonic_bin_str)
        # Convert entropy hash to binary string
        entropy_hash_bin_str = BytesUtils.ToBinaryStr(
            CryptoUtils.Sha256(entropy_bytes),
            CryptoUtils.Sha256DigestSize() * 8)

        # Return checksum
        return entropy_hash_bin_str[:self.__GetChecksumLen(mnemonic_bin_str)]
Beispiel #22
0
    def ComputeChecksum(payload_bytes: bytes) -> bytes:
        """
        Compute checksum in EOS format.

        Args:
            payload_bytes (bytes): Payload bytes

        Returns:
            bytes: Computed checksum
        """
        return CryptoUtils.Kekkak256(
            payload_bytes)[:XmrAddrConst.CHECKSUM_BYTE_LEN]
Beispiel #23
0
    def ComputeChecksum(data_bytes: bytes) -> bytes:
        """
        Compute SS58 checksum.

        Args:
            data_bytes (bytes): Data bytes

        Returns:
            bytes: Computed checksum
        """
        return CryptoUtils.Blake2b(SS58Const.CHECKSUM_PREFIX +
                                   data_bytes)[:SS58Const.CHECKSUM_BYTE_LEN]
Beispiel #24
0
    def ComputeChecksum(data_bytes: bytes) -> bytes:
        """
        Compute Base58 checksum.

        Args:
            data_bytes (bytes): Data bytes

        Returns:
            bytes: Computed checksum
        """
        return CryptoUtils.DoubleSha256(
            data_bytes)[:Base58Const.CHECKSUM_BYTE_LEN]
Beispiel #25
0
    def ComputeChecksum(pub_key_bytes: bytes) -> bytes:
        """
        Compute checksum in Algorand format.

        Args:
            pub_key_bytes (bytes): Public key bytes

        Returns:
            bytes: Computed checksum
        """
        return CryptoUtils.Sha512_256(
            pub_key_bytes)[-1 * AlgoAddrConst.CHECKSUM_BYTE_LEN:]
Beispiel #26
0
    def ComputeChecksum(pub_key_bytes: bytes) -> bytes:
        """
        Compute checksum in EOS format.

        Args:
            pub_key_bytes (bytes): Public key bytes

        Returns:
            bytes: Computed checksum
        """
        return CryptoUtils.Ripemd160(
            pub_key_bytes)[:EosAddrConst.CHECKSUM_BYTE_LEN]
Beispiel #27
0
    def ComputeChecksum(data_bytes: bytes) -> bytes:
        """
        Compute checksum.

        Args:
            data_bytes (bytes): Data bytes

        Returns:
            bytes: Computed checksum
        """
        return CryptoUtils.Sha512_256(
            data_bytes)[:AlgorandMnemonicConst.CHECKSUM_BYTE_LEN]
Beispiel #28
0
    def ComputeChecksum(pub_key_bytes: bytes) -> bytes:
        """
        Compute checksum in Nano format.

        Args:
            pub_key_bytes (bytes): Public key bytes

        Returns:
            bytes: Computed checksum
        """
        return BytesUtils.Reverse(
            CryptoUtils.Blake2b(pub_key_bytes,
                                digest_size=NanoAddrConst.CHECKSUM_BYTE_LEN))
Beispiel #29
0
    def __ViewFromSpendKey(priv_skey: MoneroPrivateKey) -> MoneroPrivateKey:
        """
        Get the private view key from the private spend key.

        Args:
            priv_skey (MoneroPrivateKey object): Private spend key

        Returns:
            MoneroPrivateKey object: Private view key
        """
        priv_vkey_bytes = _MoneroUtils.ScReduce(
            CryptoUtils.Kekkak256(priv_skey.Raw().ToBytes()))
        return MoneroPrivateKey.FromBytes(priv_vkey_bytes)
Beispiel #30
0
    def ComputeKeys(self,
                    minor_idx: int,
                    major_idx: int) -> Tuple[MoneroPublicKey, MoneroPublicKey]:
        """
        Compute the public keys of the specified subaddress.

        Args:
            minor_idx (int): Minor index (i.e. subaddress index)
            major_idx (int): Major index (i.e. account index)

        Returns:
            tuple[MoneroPublicKey, MoneroPublicKey]: Computed public spend key (index 0) and public view key (index 1)

        Raises:
            ValueError: If one of the indexes is not valid
        """
        if minor_idx < 0 or minor_idx > MoneroSubaddressConst.SUBADDR_MAX_IDX:
            raise ValueError(f"Invalid minor index ({minor_idx})")
        if major_idx < 0 or major_idx > MoneroSubaddressConst.SUBADDR_MAX_IDX:
            raise ValueError(f"Invalid major index ({major_idx})")

        # Subaddress 0,0 is the primary address
        if minor_idx == 0 and major_idx == 0:
            return self.m_pub_skey, self.m_pub_vkey

        # Convert indexes to bytes
        major_idx_bytes = IntegerUtils.ToBytes(major_idx,
                                               bytes_num=MoneroSubaddressConst.SUBADDR_IDX_BYTE_LEN,
                                               endianness="little")
        minor_idx_bytes = IntegerUtils.ToBytes(minor_idx,
                                               bytes_num=MoneroSubaddressConst.SUBADDR_IDX_BYTE_LEN,
                                               endianness="little")

        # m = Kekkak256("SubAddr" + master_priv_vkey + major_idx + minor_idx)
        m = CryptoUtils.Kekkak256(MoneroSubaddressConst.SUBADDR_PREFIX
                                  + self.m_priv_vkey.Raw().ToBytes()
                                  + major_idx_bytes
                                  + minor_idx_bytes)
        m_int = BytesUtils.ToInteger(m, endianness="little")

        # Compute subaddress public spend key
        # D = master_pub_skey + m * B
        subaddr_pub_skey_point = self.m_pub_skey.KeyObject().Point() + (Ed25519Monero.Generator() * m_int)

        # Compute subaddress public view key
        # C = master_priv_vkey * D
        subaddr_pub_vkey_point = subaddr_pub_skey_point * self.m_priv_vkey.Raw().ToInt("little")

        return (MoneroPublicKey.FromBytes(subaddr_pub_skey_point.RawEncoded().ToBytes()),
                MoneroPublicKey.FromBytes(subaddr_pub_vkey_point.RawEncoded().ToBytes()))