Simple builder and utility functions for creating Shamir secret shares and secret reconstruction.
- Shamir secret sharing wiki
- Credit to Stackoverflow user JerzySkalski for providing a working example which limits the finite field with prime modulus division.
- Shamir.java: Minimal static methods to facilitate the creation of shares and the reconstruction of a secret.
- ShamirSharesBuilder.java: A mutable builder to help coordinate the state needed to create and validate shares.
- Required Shares: The minimum number of shares needed to reconstruct the free coefficient secret.
- Total Shares: The total number of shares to generate.
- Prime:
- Must be supplied directly, or indirectly as a Mersenne Prime exponent.
- Must be larger than all secrets used.
- Random: Defaults to
new SecureRandom()
- Secret:
- May be provided as a byte[] or a BigInteger to
initSecrets(secret)
. - Defaults to a random value in the range (0, prime) with a call to
initSecrets()
.
- May be provided as a byte[] or a BigInteger to
var sharesBuilder = Shamir.buildShares()
.numRequiredShares(3)
.numShares(5)
.mersennePrimeExponent(521)
.initSecrets("Shamir's Secret".getBytes(UTF_8));
BigInteger[] shares = sharesBuilder.createShares();
// Validate secret reconstruction for all share combinations of size 'numRequiredShares'.
// Throws an IllegalStateException if any reconstructed secret does not equal the original.
sharesBuilder.validateShareCombinations(shares);
// Reconstruct secret.
var coordinates = Map.of(BigInteger.valueOf(1), shares[0],
BigInteger.valueOf(3), shares[2],
BigInteger.valueOf(5), shares[4]);
var secret = Shamir.reconstructSecret(coordinates, sharesBuilder.getPrime());
var secretString = new String(secret.toByteArray(), UTF_8);