{"id":19513553,"url":"https://github.com/atropinetears/num-primes","last_synced_at":"2025-04-26T05:32:05.934Z","repository":{"id":45583991,"uuid":"260989972","full_name":"AtropineTears/num-primes","owner":"AtropineTears","description":"A Rust Library For Generating Large Composite, Prime, and Safe Prime Numbers","archived":false,"fork":false,"pushed_at":"2021-12-07T05:07:59.000Z","size":82,"stargazers_count":9,"open_issues_count":3,"forks_count":7,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-04T08:05:08.660Z","etag":null,"topics":["bignum","composite-numbers","crypto","cryptography","csprng","generating-primes","generator","library","num","num-bigint","num-traits","prime-factors","prime-numbers","primes","random","rust","rust-lang","safe-prime","smooth-numbers","verify"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AtropineTears.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-05-03T18:02:33.000Z","updated_at":"2025-03-09T09:50:11.000Z","dependencies_parsed_at":"2022-09-07T20:23:03.155Z","dependency_job_id":null,"html_url":"https://github.com/AtropineTears/num-primes","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtropineTears%2Fnum-primes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtropineTears%2Fnum-primes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtropineTears%2Fnum-primes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtropineTears%2Fnum-primes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AtropineTears","download_url":"https://codeload.github.com/AtropineTears/num-primes/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250937222,"owners_count":21510923,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bignum","composite-numbers","crypto","cryptography","csprng","generating-primes","generator","library","num","num-bigint","num-traits","prime-factors","prime-numbers","primes","random","rust","rust-lang","safe-prime","smooth-numbers","verify"],"created_at":"2024-11-10T23:30:49.293Z","updated_at":"2025-04-26T05:32:05.554Z","avatar_url":"https://github.com/AtropineTears.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Num-Primes: CSPRNG Large Composite, Prime, Safe Prime Generator\n\n[![Crates.io](https://img.shields.io/crates/v/num-primes?style=flat-square)](https://crates.io/crates/num-primes)\n![Crates.io](https://img.shields.io/crates/l/num-primes?style=flat-square)\n\nThis crate provides a **beautifully simplistic API** for generating large, cryptographically-random, unsigned integers in rust, including but not limited to **composite, prime, and safe prime numbers**.\n\nIt takes full advantage of the [num](https://crates.io/crates/num) crate on **stable rust**.\n\n* Read the [About](#about)\n* Read the [License](#license)\n* Read the [Contribution](#contribution)\n\n## Notice\n\nPlease note there is a critical bug in this program that I cannot seem to fix where it marks some prime numbers as not prime. It is in the miller-rabin implementation and I cannot seem to fix it. If anyone is up to it, feel free to look through the issues tab for information about the bug and submit a PR if you find a fix.\n\n## Usage\n\nAdd this to your `Cargo.toml`:\n\n```toml\n[dependencies]\nnum-primes = \"0.2.0\"\n```\n\n## Warning\n\nThere is currently a major bug in `is_prime()` and `is_composite()` that makes some values return wrong. For example, a prime can sometimes be marked as composite unless it was generated as they use the same tests to test for primality.\n\n## How To Use\n\nThere are three main structs that are included in this library\n\n| Structs       | Description                                                  |\n| ------------- | ------------------------------------------------------------ |\n| Generator     | Allows the **random generation** of composite numbers, prime numbers, and safe prime numbers. |\n| Verification  | Allows the **verification** of composite, prime, safe prime, and very smooth numbers. |\n| Factorization | Allows the **factorization** of Composite and Prime Numbers into their largest Prime Factor. |\n\n## Generator\n\n### Generate Composite Number\n\nThis function will generate a **composite number** of `n-bits`.\n\n```rust\nuse num_primes::Generator;\n\nfn main(){\n  // Generate Composite of 1024 bits\n  let composite = Generator::new_composite(1024);\n}\n```\n\n### Generate Prime Number\n\nThis function will generate a **prime number** of `n-bits`.\n\n```rust\nuse num_primes::Generator;\n\nfn main(){\n  // Generate two primes (p,q) of 512 bits each\n  let p = Generator::new_prime(512);\n  let q = Generator::new_prime(512);\n  \n  // Multiply to get the modulus (n)\n  let n = p * q;\n}\n```\n\n### Generate Safe Prime\n\nThis function will generate a **safe prime number** of `n-bits`. This function uses the [same tests openssl uses](https://www.openssl.org/docs/man1.1.1/man1/openssl-prime.html) to generate safe primes, which is `(n-1)/2`.\n\nThis function is quite time consuming and should be avoided for large sizes.\n\n```rust\nuse num_primes::Generator;\n\nfn main(){\n  // Generate Safe Prime of 64 bits | Uses (n-1)/2 to check\n  let safe_prime = Generator::safe_prime(64);\n}\n```\n\n### Generate Large Unsigned Integer\n\nThis function will generate a **large unsigned integer** of `n-bits`. This function is **faster** than generating a composite or prime number due to no checks being done.\n\n```rust\nuse num_primes::Generator;\n\nfn main(){\n  // Generate a Large Unsigned Integer of 1024 bits without running any checks\n  let x = Generator::new_uint(1024);\n}\n```\n\n## Verification\n\nWARNING: There is currently a bug that makes verification of certain prime numbers fail. Be careful when using this feature.\n\n### Verify Composite Number\n\nThis function will verify whether a `BigUint` type is a **composite** by returning a boolean value.\n\n```rust\nuse num_primes::{Generator,Verification};\n\nfn main(){\n  // Generates Composite Number of 1024 bits\n  let x = Generator::new_composite(1024);\n  \n  // Check if the number is a Composite Number\n  let is_composite: bool = Verification::is_composite(\u0026x);\n  \n  // Asserts that 'is_composite' is true\n  assert_eq!(is_composite, true);\n}\n```\n\n### Verify Prime Number\n\nThis function will verify whether a `BigUint` type is a **prime** by returning a boolean value.\n\n```rust\nuse num_primes::{Generator,Verification};\n\nfn main(){\n  // Generates Prime Number of 1024 bits\n  let x = Generator::new_prime(1024);\n  \n  // Check if the number is a Prime Number\n  let is_prime: bool = Verification::is_prime(\u0026x);\n  \n  // Asserts that 'is_prime' is true\n  assert_eq!(is_prime, true);\n}\n```\n\n### Verify Safe Prime Number\n\nThis function will verify whether a `BigUint` type is a **safe prime** by returning a boolean value.\n\n```rust\nuse num_primes::{Generator,Verification};\n\nfn main(){\n  // Generates a Safe Prime Number of 128 bits\n  let x = Generator::safe_prime(128);\n  \n  // Check if the number is a Safe Prime Number\n  let is_safe_prime: bool = Verification::is_safe_prime(\u0026x);\n  \n  // Asserts that `is_safe_prime` is true\n  assert_eq!(is_safe_prime, true);\n}\n```\n\n### [Experimental] Verify VSN (Smooth Numbers)\n\n**EXPERIMENTAL: Please Avoid Using This Function As Of Now**\n\nRead [Wolfram Alpha - Smooth Numbers](https://mathworld.wolfram.com/SmoothNumber.html)\n\nRead [OEIS - P-Smooth Numbers](http://oeis.org/wiki/P-smooth_numbers)\n\nRead [Wikipedia - Examples of VSN and VSSR](https://en.wikipedia.org/wiki/Very_smooth_hash#Examples_of_VSN_and_VSSR)\n\n---\n\nThis function will verify whether a number is a **very smooth number**. It accepts three parameters as follows:\n\n- m: `\u0026BigUint` | prime\n- n: `f64` | constant\n- c: `u32` | constant\n\nIt follows the following equation:\n\n\u003e 1. Return `m`'s **Greatest Prime Factor** as `p`\n\u003e    1. if `p` `\u003c=` `log(n)`\u003csup\u003e`c`\u003c/sup\u003e then its **p-smooth**\n\u003e    2. if `p` `\u003e` `log(n)`\u003csup\u003e`c`\u003c/sup\u003e then its **not p-smooth**\n\n```rust\nuse num::traits::FromPrimitive;\nuse num_bigint::BigUint;\nuse num_primes::Verification;\n\nfn main() {\n    // Set BigUint To 7u64\n    let x: BigUint = BigUint::from_u64(7u64).unwrap();\n\n    // Verify Its A Smooth Number with parameters \n  \t\t// m = 7 (\u0026BigUint)\n  \t\t// n = 31.0 (f64)\n  \t\t// c = 5 (u32)\n    let result: bool = Verification::is_very_smooth_number(\u0026x,31.0,5);\n\n  \t// Print What Type of Smooth Number It Is And Whether Or Not It Is Smooth\n    println!(\"Is A {} Smooth Number: {}\",x,result);\n  \n  \t// This problem should be 7-smooth\n  \tassert_eq!(result, true);\n}\n```\n\n## Factorization\n\n**NOTICE:** Factorization is still in the works.\n\n### Prime Factorization\n\nRead [GeeksforGeeks - Efficient program to print all prime factors of a given number](https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/)\n\n---\n\nThis function lets you **factorize** composite numbers and prime numbers to find their **Greatest Prime Factor**.\n\n```rust\nuse num_primes::{Generator,Factorization};\n\nfn main() {\n    // Generates New Unsighed Integer of 32 bits\n    let uint = Generator::new_uint(32);\n    \n  \t// Prime Factorization Returns Option\u003cBigUint\u003e    \n    let factor = Factorization::prime_factor(uint);\n\n  \t// match the Option\u003cBigUint\u003e\n    match factor {\n        Some(factor) =\u003e println!(\"Largest Prime Factor: {}\",factor),\n        None =\u003e println!(\"No Prime Factors Found\"),\n    }\n}\n```\n\n#### How Does It Work\n\nThe steps are listed below with `n` being the **input number** being factored:\n\nA **Primality Check** is used first to determine whether the number is a prime or not.\n\n1. while `n` is even, divide by 2\n2. After Step 1, `n` must be odd.\n   1. `n_sqrt` = Take the square root of `n`\n3. Start a loop from `i = 3` to `n_sqrt`\n   1. While `i` / `n`\n      1. Divide `n` by `i`\n   2. On Failure of `i` dividing by `n`,\n      1. increment `i` by 2 and continue\n4. If `n` is a prime number and `n` \u003e `2`\n   1. Return `n`\n\n---\n\n# About\n\n## Prime Number Generation Design\n\nThe Prime Number Generation and parts of its code is based on [Snips-AI's Medium Blog on Generating Prime Numbers](https://medium.com/snips-ai/prime-number-generation-2a02f28508ff).\n\nA **conservative attempt** is made at deciding whether a number is prime or not. The number goes through the generation phase and 3 tests to determine if its prime:\n\n### Generation Phase\n\n1. A single parameter is passed to the generator function that indicates the number of bits the prime should be.\n\n2. The userspace CSPRNG is seeded by the operating system to generate the random numbers using the rand crate.\n\n3. An unsigned integer is generated until it passes the prime test.\n\n4. The number is sent to be processed by **four tests**\n\n### Primality Tests\n\nThe numbers go through multiple tests to determine whether they are composite or prime.\n\n1. A check is done to see if the number is even.\n2. An array of the first **2048 primes** is used to check whether the number is divisble by any of the primes in the array.\n3. **Fermat's Little Theorem** is performed\n4. **Miller-Rabin Primality Test**, the gold standard recommended by the official RSA documentation and by [NIST](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf) on generating primes, is performed with **16 iterations**, the same used by Apple's cryptosystem.\n\nIf the number passes these tests, it is considered with high probability to be prime. Feel free to verify them yourselves on [Wolfram Alpha](https://www.wolframalpha.com/) by simply typing in the prime number.\n\n### Safe Primes\n\n**Safe Primes** are generated simply by checking if `(p-1)/2` is a prime with the tests listed above.\n\n## OpenSSL-Prime vs. Num-Primes\n\n\u003e https://security.stackexchange.com/questions/176394/how-does-openssl-generate-a-big-prime-number-so-fast\n\n**OpenSSL LTS (1.1.1)** has a [doc page](https://www.openssl.org/docs/man1.1.1/man1/openssl-prime.html) for **prime generation**, including how safe primes are generated. \n\n\u003e OpenSSL should be prefered for serious cryptographic implementations due to the security of their code and their code having been audited.\n\nNum-Primes may be useful in certain situations, like in embedded systems or where OpenSSLis overkill.\n\n---\n\n**OpenSSL-prime:**\n\n* Generates **Safe Primes** using `(n-1)/2` but is much more efficient\n* Performs a **default** of **20 checks** on prime numbers.\n\n**Num-Primes:**\n\n* Generates **Safe Primes** using `(n-1)/2` but takes much longer for unknown reasons\n* Performs a **default** of **16 checks** on prime numbers through 4 different primality tests\n* Supports #[no_std] and stable rust\n* May be useful in situations where using OpenSSL would be overkill.\n\n## Differences Between `num-primes` and `ramp-primes`\n\n[ramp-primes](https://github.com/0xSilene/ramp-primes) is the **original implementation** of the prime number generator using the **ramp** library.\n\n[num-primes](https://github.com/0xSilene/num-primes) is the **improved implementation** using the **num** library and is available on **stable release** with **no_std** support.\n\n### num-primes (Stable)\n\nUses [num](https://crates.io/crates/num), a **pure-rust implementation** for **numeric types and traits**.\n\n* **num** is **stable** and can work on the **Default, Beta, and Nightly Branch**\n\n* **num** is in **Pure Rust**\n* **num** implements more **features**\n* **num** has around **~6,000,000 downloads**\n* **num** is more developed than **ramp**.\n\n**num-primes** has:\n\n* **Better API** and **Documentation**\n* More **Functionality**\n* **no_std support**\n\n### ramp-primes (Unstable)\n\nUses [ramp](https://crates.io/crates/ramp), a **high-performance multiple-precision** (aka \"BigNum\") library for working with numbers bigger than can normally be handled.\n\n* **ramp** only works on **unstable rust** (the nightly branch).\n* **ramp** is written in **Rust** and **Inline Assembly** (security concern)\n* **ramp** is generally **faster**\n* **ramp** is specifically focused on **multiple-precision arithmetic**\n* **ramp** has around **~17,000 downloads**\n* **ramp** is not as developed as **num**\n\n**ramp-primes** is:\n\n* The First Implementation\n* Generally **Faster** For Generation\n* Less Features\n* Only Works On **Unstable Rust** (Nightly Build)\n\n# License\n\nLicensed under either of\n\n* Apache License, Version 2.0\n\n* MIT license\n\nat your option.\n\n# Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatropinetears%2Fnum-primes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fatropinetears%2Fnum-primes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatropinetears%2Fnum-primes/lists"}