71 lines
1.9 KiB
Java
71 lines
1.9 KiB
Java
/*
|
|
* Copyright (c) 2014-2021 Thetya Team
|
|
* Copyright (c) 2005-2011 Three Rings
|
|
*
|
|
* https://github.com/Thetya
|
|
*/
|
|
|
|
package com.github.thetya.tools;
|
|
|
|
import static com.github.thetya.tools.Log.log;
|
|
|
|
import com.threerings.presents.util.SecureUtil;
|
|
import java.io.FileWriter;
|
|
import java.io.IOException;
|
|
import java.security.KeyPair;
|
|
|
|
/**
|
|
* A simple utility to generate RSA key pairs, using the {@link SecureUtil#genRSAKeyPair(int)}
|
|
* method. The generated keys are outputted to a plaintext file or the standard output, if saving to
|
|
* a file is impossible.
|
|
*/
|
|
public class RsaKeypairGenerator {
|
|
|
|
/**
|
|
* Used during the key pair generation, determines the key bits.
|
|
*/
|
|
private static int keyBits = 2048;
|
|
|
|
public static void main(final String... args) {
|
|
if (args.length > 0) {
|
|
try {
|
|
keyBits = Integer.parseInt(args[0]);
|
|
} catch (NumberFormatException e) {
|
|
log.warning(
|
|
"The passed argument is not an integer, falling back to the default key bits value.",
|
|
"input",
|
|
args[0]);
|
|
}
|
|
}
|
|
|
|
log.info("Generating a new RSA key pair...", "keyBits", keyBits);
|
|
|
|
// First generate the key pair itself.
|
|
final KeyPair rsaKeyPair = SecureUtil.genRSAKeyPair(keyBits);
|
|
|
|
// Now get the keys
|
|
final String privateKey = SecureUtil.RSAKeyToString(rsaKeyPair.getPrivate());
|
|
final String publicKey = SecureUtil.RSAKeyToString(rsaKeyPair.getPublic());
|
|
|
|
try {
|
|
final FileWriter writer = new FileWriter("keys.txt");
|
|
writer.append("PUBLIC KEY\n");
|
|
writer.append(publicKey);
|
|
writer.append("\n\n");
|
|
writer.append("PRIVATE KEY\n");
|
|
writer.append(privateKey);
|
|
|
|
writer.flush();
|
|
writer.close();
|
|
|
|
log.info("Done, see keys.txt.");
|
|
} catch (IOException e) {
|
|
log.warning(
|
|
"Could not open a file writer, outputting the keys to the log instead.",
|
|
"public",
|
|
publicKey,
|
|
"private",
|
|
privateKey);
|
|
}
|
|
}
|
|
} |