How do i represent this in rust?

integer literal is too large
value exceeds limit of 0xffffffffffffffffffffffffffffffff when i put the low/high in rust

import random
def generate_private_key():
    low  = 0x18909BDE11F67C97A53C62F45E632EAB58EA0D73A5FAC9EB50295FAD40A57EB5
    high = 0xDD10559E1285B3EE0303B159B8D6D8D0B88E6168D1C1D6000000000000000000
    return str( hex( random.randrange( low, high ) ) )

You can use a big-integer library, like num-bigint. This will give you the same functionality that Python is using implicitly.

1 Like

Note: Use rug if you are ok with LGPL license. num-bigint's runtime performance is horrible.

1 Like

what about a random range i don't see that

num has a rand feature, and rug also has a rand feature for some built-in implementation I'm not familiar with.

The rand crate also has a packed_simd feature which could perhaps be used for the OP.

(Sadly none of these complete combinations are available in the playground.)

1 Like

wont simd be used by default

It seems your key has a fixed size, in that case it would be more efficient to use something like bnum, which provides arbitrary but fixed sized integers. It also has an optional rand feature to enable integration with the rand crate.

/*
[dependencies]
bnum = { version = "0.11", features = ["rand"] }
rand = "0.8"
*/

use bnum::types::U256;
use rand::Rng;

fn generate_private_key() -> U256 {
    const LOW: U256 = U256::parse_str_radix(
        "18909BDE11F67C97A53C62F45E632EAB58EA0D73A5FAC9EB50295FAD40A57EB5",
        16,
    );
    const HIGH: U256 = U256::parse_str_radix(
        "DD10559E1285B3EE0303B159B8D6D8D0B88E6168D1C1D6000000000000000000",
        16,
    );

    rand::thread_rng().gen_range(LOW..HIGH)
}

fn generate_private_key_hex() -> String {
    format!("0x{:064x}", generate_private_key())
}

In theory, yes, using a dedicated crate for fixed size integer would be better. But in reality, bnum's performance falls off very quick. Multiplying two U512 takes about 4x more time than rug, Multiplying two U1024 takes about 100x.

can you show an example of getting a random 256 bit key from a low and high set of 256 bit key range in rug?
also i want the output key to be a [u8]

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.