Skip to content

Commit

Permalink
Add "entropy" key generator type
Browse files Browse the repository at this point in the history
  • Loading branch information
mikera committed Aug 7, 2024
1 parent 54916c7 commit af14b98
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
23 changes: 22 additions & 1 deletion convex-cli/src/main/java/convex/cli/key/KeyGenerate.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package convex.cli.key;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;

import convex.cli.CLIError;
import convex.cli.Constants;
import convex.cli.ExitCodes;
import convex.core.crypto.AKeyPair;
import convex.core.crypto.BIP39;
import convex.core.data.ABlob;
import convex.core.data.Blob;
import convex.core.data.Blobs;
import convex.core.data.Hash;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

Expand Down Expand Up @@ -38,7 +43,7 @@ public class KeyGenerate extends AKeyCommand {

@Option(names={"--type"},
defaultValue="bip39",
description="Type of key generation. Supports random, bip39")
description="Type of key generation. Supports random, bip39, entropy")
private String type;

@Option(names="--passphrase",
Expand Down Expand Up @@ -70,6 +75,22 @@ private AKeyPair generateKeyPair() {
return result;
} else if ("random".equals(type)) {
return AKeyPair.generate();
} else if ("entropy".equals(type)) {
if (!isInteractive()) throw new CLIError(ExitCodes.USAGE,"Entropy based genration requires interactive mode");
inform("Press some random keys to generate entropy. Press ENTER to finish.");
Hash h=Blob.createRandom(new SecureRandom(), 64).getContentHash();
while (true) {
try {
int c=System.console().reader().read();
ABlob entropy=Blobs.forLong(c).append(Blobs.forLong(System.currentTimeMillis()));
h=h.append(entropy).getContentHash();
println(h.getContentHash());
if ((c=='\r')||(c=='\n')) break;
} catch (IOException e) {
throw new CLIError(ExitCodes.IOERR,"Unable to collect entropy");
}
}
return AKeyPair.create(h.toFlatBlob());
} else {
throw new CLIError(ExitCodes.USAGE,"Unsupprted key generation type: "+type);
}
Expand Down
9 changes: 9 additions & 0 deletions convex-core/src/main/java/convex/core/data/Blobs.java
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,13 @@ public static byte[] ensureZeroBasedArray(AArrayBlob b) {
}
}

/**
* Create a 8-byte Blob representing a long value
*/
public static Blob forLong(long c) {
byte[] bs=new byte[8];
Utils.writeLong(bs, 0, c);
return Blob.wrap(bs);
}

}

0 comments on commit af14b98

Please sign in to comment.