-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathGenerateKeyPairEC.java
51 lines (46 loc) · 2.09 KB
/
GenerateKeyPairEC.java
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
/**
* This file only serves as an example on how to get keys in the right encoding. In order to use it
* you need BouncyCastle on the classpath!
*
* <p>DO NOT USE THEM IN PRODUCTION UNLESS THE KEYSPECS ARE OK FOR YOU
*/
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;
import java.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
public class GenerateKeyPairEC {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Security.setProperty("crypto.policy", "unlimited");
KeyPairGenerator generator = KeyPairGenerator.getInstance("ECDSA", "BC");
ECGenParameterSpec spec = new ECGenParameterSpec("secp256r1");
generator.initialize(spec);
KeyPair pair = generator.genKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();
StringWriter privateKeyWriter = new StringWriter();
PemWriter privateKeyPemWriter = new PemWriter(privateKeyWriter);
privateKeyPemWriter.writeObject(new PemObject("PRIVATE KEY", privateKey.getEncoded()));
privateKeyPemWriter.flush();
privateKeyPemWriter.close();
StringWriter publicKeyWriter = new StringWriter();
PemWriter publicKeyPemWriter = new PemWriter(publicKeyWriter);
publicKeyPemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
publicKeyPemWriter.flush();
publicKeyPemWriter.close();
FileOutputStream outputStream = new FileOutputStream("generated_pub.pem");
outputStream.write(Base64.getEncoder().encode(publicKeyWriter.toString().getBytes()));
outputStream.close();
outputStream = new FileOutputStream("generated_private.pem");
outputStream.write(Base64.getEncoder().encode(privateKeyWriter.toString().getBytes()));
outputStream.close();
}
}