-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRSAKeyCreation.java
74 lines (60 loc) · 2.58 KB
/
RSAKeyCreation.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAKeyGenParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
public class RSAKeyCreation {
/**
* @param args
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeySpecException
* @throws IOException
*/
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException, IOException {
if (args.length != 1) {
System.out.println("Usage: java RSAKeyCreation <name>");
}
String name = args[0];
// Beispiel: java RSAKeyCreation KMueller
// erzeugt die Ausgabedateien KMueller.pub und KMueller.prv
RSAKeyGenParameterSpec rsaKeyGenParameterSpec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(rsaKeyGenParameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
KeyFactory keyFac = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubKey = keyFac.getKeySpec(keyPair.getPublic(), X509EncodedKeySpec.class);
PKCS8EncodedKeySpec prvKey = keyFac.getKeySpec(keyPair.getPrivate(), PKCS8EncodedKeySpec.class);
byte[] pubEncoded = pubKey.getEncoded();
byte[] prvEncoded = prvKey.getEncoded();
DataOutputStream pubOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(String.format("%s.pub",name))));
DataOutputStream prvOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(String.format("%s.prv",name))));
// 1. LŠnge des Inhaber-Namens (integer)
pubOut.writeInt(name.getBytes().length);
prvOut.writeInt(name.getBytes().length);
// 2. Inhaber-Name (Bytefolge)
pubOut.writeBytes(name);
prvOut.writeBytes(name);
// 3. LŠnge des SchlŸssels (integer)
pubOut.writeInt(pubEncoded.length);
prvOut.writeInt(prvEncoded.length);
// 4. SchlŸssel (Bytefolge)
pubOut.write(pubEncoded); // [X.509-Format]
prvOut.write(prvEncoded); // [PKCS8-Format]
// close
pubOut.close();
prvOut.close();
}
}