-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenRsa.java
More file actions
52 lines (46 loc) · 1.84 KB
/
GenRsa.java
File metadata and controls
52 lines (46 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
public class GenRsa {
public static void main(String[] args) throws Exception {
int keySize = 2048;
String privateKeyPath = "private_key.pem";
String publicKeyPath = "public_key.pem";
if (args.length >= 1) {
keySize = Integer.parseInt(args[0]);
}
if (args.length >= 2) {
privateKeyPath = args[1];
}
if (args.length >= 3) {
publicKeyPath = args[2];
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(keySize);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();
// Write private key in PKCS#8 PEM format
String privatePem = "-----BEGIN PRIVATE KEY-----\n"
+ Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(privateKey.getEncoded())
+ "\n-----END PRIVATE KEY-----\n";
try (FileWriter fw = new FileWriter(privateKeyPath)) {
fw.write(privatePem);
}
// Write public key in X.509 PEM format
String publicPem = "-----BEGIN PUBLIC KEY-----\n"
+ Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(publicKey.getEncoded())
+ "\n-----END PUBLIC KEY-----\n";
try (FileWriter fw = new FileWriter(publicKeyPath)) {
fw.write(publicPem);
}
System.out.println("RSA keypair generated.");
System.out.println("Private key: " + privateKeyPath);
System.out.println("Public key: " + publicKeyPath);
}
}