*** empty log message ***
[thera-pi.git] / Nebraska / src / org / thera_pi / nebraska / gui / NebraskaRequestDlg.java
blob7200fa4a4ccd6522baf2f0af872e9d350e8d37ee
1 package org.thera_pi.nebraska.gui;
3 import java.awt.BorderLayout;
4 import java.awt.Color;
5 import java.awt.Dimension;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.ActionListener;
8 import java.io.File;
9 import java.io.FileNotFoundException;
10 import java.io.FileOutputStream;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.math.BigInteger;
14 import java.net.HttpURLConnection;
15 import java.net.InetAddress;
16 import java.net.MalformedURLException;
17 import java.net.URL;
18 import java.net.UnknownHostException;
19 import java.security.MessageDigest;
20 import java.security.NoSuchAlgorithmException;
21 import java.security.NoSuchProviderException;
22 import java.security.cert.X509Certificate;
23 import java.util.Vector;
25 import javax.swing.JButton;
26 import javax.swing.JDialog;
27 import javax.swing.JLabel;
28 import javax.swing.JOptionPane;
29 import javax.swing.SwingUtilities;
31 import nebraska.BCStatics2;
32 import nebraska.Constants;
33 import nebraska.FileStatics;
34 import nebraska.Nebraska;
36 import org.bouncycastle.asn1.ASN1Object;
37 import org.bouncycastle.asn1.ASN1Sequence;
38 import org.bouncycastle.asn1.ASN1Set;
39 import org.bouncycastle.asn1.pkcs.CertificationRequestInfo;
40 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
41 import org.bouncycastle.jce.PKCS10CertificationRequest;
42 import org.jdesktop.swingx.JXHeader;
43 import org.jdesktop.swingx.JXPanel;
44 import org.thera_pi.nebraska.crypto.NebraskaConstants;
45 import org.thera_pi.nebraska.crypto.NebraskaCryptoException;
46 import org.thera_pi.nebraska.crypto.NebraskaFileException;
47 import org.thera_pi.nebraska.crypto.NebraskaKeystore;
48 import org.thera_pi.nebraska.crypto.NebraskaNotInitializedException;
49 import org.thera_pi.nebraska.gui.utils.ButtonTools;
50 import org.thera_pi.nebraska.gui.utils.DatFunk;
51 import org.thera_pi.nebraska.gui.utils.JRtaComboBox;
52 import org.thera_pi.nebraska.gui.utils.JRtaTextField;
53 import org.thera_pi.nebraska.gui.utils.MultiLineLabel;
58 import utils.NUtils;
59 import utils.OOorgTools;
60 import CommonTools.INIFile;
62 import com.jgoodies.forms.layout.CellConstraints;
63 import com.jgoodies.forms.layout.FormLayout;
65 public class NebraskaRequestDlg extends JDialog{
67 /**
70 private static final long serialVersionUID = 6958116962234351720L;
72 private JRtaTextField pw = null;
73 private JButton[] buts = {null,null,null,null};
74 private ActionListener al = null;
75 private NebraskaZertAntrag zertantrag = null;
76 private JXPanel content = null;
77 private JLabel[] labs = {null,null,null};
78 private MultiLineLabel[] mlabs = {null,null,null,null};
79 private String pathtokeystoredir = null;
80 private String pathtoprivkeydir = null;
81 private String ik = null;
82 private String institution = null;
83 private String person = null;
84 NebraskaKeystore keystore = null;
86 public NebraskaRequestDlg(NebraskaZertAntrag zertantrag,boolean importiert,String therapidir){
87 super();
88 this.activateListeners();
89 this.setTitle("4 Schritte zum Zertifikatsrequest");
91 this.zertantrag = zertantrag;
92 this.ik = zertantrag.getIK();
93 this.institution = zertantrag.getInstitution();
94 this.person = zertantrag.getPerson();
96 if(this.ik.equals("") || this.institution.equals("") || this.person.equals("") ){
97 JOptionPane.showMessageDialog(null,"IK, Antragsteller und Ansprechpartner dürfen nicht leer sein");
98 this.dispose();
99 return;
102 this.content = this.contentPanel();
104 if(importiert){
105 System.out.println("nehme getImportPanel()");
106 pathtokeystoredir = (therapidir+File.separator+"keystore"+File.separator+ik).replace("\\", "/");
107 pathtoprivkeydir = (pathtokeystoredir+File.separator+"privkeys").replace("\\", "/");
108 this.content.add(getImportPanel(importiert,therapidir,ik),BorderLayout.CENTER);
109 }else{
110 System.out.println("nehme getStandAlonePanel()");
111 this.content.add(getStandAlonePanel(),BorderLayout.CENTER);
113 this.setContentPane(this.content);
114 this.getContentPane().setPreferredSize(new Dimension(800,400));
115 this.getContentPane().validate();
118 /*****
119 * Für Benutzer von Thera-Pi, die die Mandantendaten zuvor importiert haben
120 * @param importiert
121 * @param therapidir
122 * @param ik
123 * @return
126 private JXPanel getImportPanel(boolean importiert,String therapidir,String ik){
127 // 1 2 3 4 5 6 7 8 9
128 FormLayout lay = new FormLayout("0dlu,fill:0:grow(0.5),p,10dlu,p,5dlu,50dlu,fill:0:grow(0.5),0dlu",
129 // 1 2 3 4 5 6 7 8 9
130 "fill:0:grow(0.5),p,15dlu,p,15dlu,p,15dlu,p,fill:0:grow(0.5)");
131 CellConstraints cc = new CellConstraints();
132 JXPanel jpan = new JXPanel();
133 jpan.setLayout(lay);
134 mlabs[0] = new MultiLineLabel("1. Verzeichnis der Zertifikatsdatenbank\n(Bei Import aus Thera-Pi fest vorgegeben)",0,0);
135 mlabs[0].setAlignment(MultiLineLabel.RIGHT);
136 jpan.add(mlabs[0],cc.xy(3, 2,CellConstraints.RIGHT,CellConstraints.CENTER));
137 labs[0] = new JLabel(pathtokeystoredir);
138 labs[0].setForeground(Color.RED);
139 jpan.add(labs[0],cc.xy(5, 2));
140 jpan.add( (buts[0]=ButtonTools.macheBut("ändern", "edit", al)),cc.xy(7,2) );
141 buts[0].setEnabled(false);
142 mlabs[1] = new MultiLineLabel("2. Passwort für die Zertifikatsdatenbank eingeben (max.6 Zeichen!)\n(Sinniger Weise ist diese Passwort fest vorgegeben!!!)",0,0);
143 mlabs[1].setAlignment(MultiLineLabel.RIGHT);
144 jpan.add(mlabs[1],cc.xy(3, 4,CellConstraints.RIGHT,CellConstraints.CENTER));
145 pw = new JRtaTextField("nix",true);
146 pw.setText("123456");
147 pw.setEditable(false);
148 jpan.add(pw,cc.xy(5,4));
149 jpan.add( (buts[1]=ButtonTools.macheBut("fixieren", "fixit", al)),cc.xy(7,4) );
151 mlabs[2] = new MultiLineLabel("3. Sodele.... jetzt das geheime Schlüsselpaar erzeugen und speichern",0,0);
152 mlabs[2].setEnabled(false);
153 jpan.add(mlabs[2],cc.xyw(3,6,3,CellConstraints.RIGHT,CellConstraints.CENTER));
154 jpan.add( (buts[2]=ButtonTools.macheBut("und los...", "generatekeypair", al)),cc.xy(7,6) );
155 buts[2].setEnabled(false);
157 mlabs[3] = new MultiLineLabel("4. Abschließend den Zertifikats-Request für die ITSG erzeugen\nund fertig ist die Laube",0,0);
158 mlabs[3].setAlignment(MultiLineLabel.RIGHT);
159 jpan.add(mlabs[3],cc.xyw(3,8,3,CellConstraints.RIGHT,CellConstraints.CENTER));
160 jpan.add( (buts[3]=ButtonTools.macheBut("und los...", "generaterequest", al)),cc.xy(7,8) );
161 buts[3].setEnabled(false);
162 jpan.validate();
163 return jpan;
166 private JXPanel getStandAlonePanel(){
167 JXPanel jpan = new JXPanel();
168 jpan.add(new JLabel("Nebraska StandAlone-Panel noch nicht entwickelt!\n\nSie müssen die Mandantendaten zuvor aus Thera-Pi importieren!"));
169 return jpan;
172 private JXPanel contentPanel(){
173 JXPanel pan = new JXPanel(new BorderLayout());
174 JXHeader jxhead = new JXHeader("Zertifikats-Request erzeugen",
175 "Gehen Sie einfach Schritt für Schritt durch die 4 angegebenen Punkte - nur keine Panik, Sie haben Zeit...\n\n" +
176 "Vergessen Sie bitte nicht Ihr gewähltes Passwort zu notieren und an sicherer Stelle zu verwahren!",null);
177 pan.add(jxhead,BorderLayout.NORTH);
178 return pan;
181 private void activateListeners(){
182 al = new ActionListener(){
183 @Override
184 public void actionPerformed(ActionEvent arg0) {
185 String cmd = arg0.getActionCommand();
186 if(cmd.equals("fixit")){
187 doFixIt();
188 return;
190 if(cmd.equals("generatekeypair")){
191 doGenerateKeys();
192 return;
194 if(cmd.equals("generaterequest")){
195 doGenerateRequest();
196 String meldung = "Der Zertifikatsrequest wurde erfolgreich erzeugt!\n\n"+
197 "Sie können nun dieses Fenster schließen, den Begleitzettel ausdrucken und dann die Datei\n\n"+
198 zertantrag.therapidir+"/keystore/"+ik+"/"+ik+".p10\n\nals Emailanhang an die ITSG senden\n"+
200 JOptionPane.showMessageDialog(null, meldung);
201 SwingUtilities.invokeLater(new Runnable(){
202 public void run(){
203 try{
204 RunAjax("http://www.thera-pi.org/html/updates.php", "updated.txt", "ZertRequest-erstellt-für-"+ik+"-"+institution.replace(" ", "_")+"-"+person.replace(" ", "_"));
205 }catch(Exception ex){
210 SwingUtilities.invokeLater(new Runnable(){
211 public void run(){
212 try{
213 macheConfig();
214 }catch(Exception ex){
218 return;
224 private void macheConfig(){
225 String osVersion = System.getProperty("os.name");
226 String confdatei = null;
227 if(osVersion.contains("Linux")){
228 confdatei = this.zertantrag.therapidir+"/nebraska_linux.conf";
229 }else if(osVersion.contains("Windows")){
230 confdatei = this.zertantrag.therapidir+"/nebraska_windows.conf";
231 }else if(osVersion.contains("Mac OS X")){
232 confdatei = "keine Ahnung..... /st.";
234 erstelleConfig(confdatei);
236 private void erstelleConfig(String configfile){
237 INIFile ifile = new INIFile(configfile);
238 boolean neuerEintrag = false;
239 int eintragBei = -1;
240 if(NebraskaMain.keyStoreParameter.size() <= 0 ){
241 neuerEintrag = true;
242 }else{
243 for(int i = 0; i < NebraskaMain.keyStoreParameter.size();i++){
244 if(ifile.getStringProperty("KeyStores", "KeyStoreAlias"+Integer.toString(i+1)).equals("IK"+this.ik)){
245 neuerEintrag = false;
246 eintragBei = i+1;
247 break;
249 neuerEintrag = true;
252 Vector<String> dummy = new Vector<String>();
254 dummy.add( ini.getStringProperty("KeyStores", "KeyStoreFile"+Integer.toString(i+1)) );
255 dummy.add( man.decrypt(ini.getStringProperty("KeyStores", "KeyStorePw"+Integer.toString(i+1))) );
256 dummy.add( ini.getStringProperty("KeyStores", "KeyStoreAlias"+Integer.toString(i+1)) );
257 dummy.add( man.decrypt(ini.getStringProperty("KeyStores", "KeyStoreKeyPw"+Integer.toString(i+1))) );
258 keyStoreParameter.add( (Vector<String>) dummy.clone() );
260 int inipos = -1;
261 if(neuerEintrag && eintragBei < 0){ //es gibt noch keinen Eintrag
262 inipos = 1;
263 dummy.add(this.zertantrag.therapidir+"/keystore/"+this.ik+"/"+this.ik+".p12");
264 dummy.add(pw.getText());
265 dummy.add("IK"+this.ik);
266 dummy.add("abc");
267 NebraskaMain.keyStoreParameter.add((Vector<String>) dummy.clone());
268 }else if(neuerEintrag && NebraskaMain.keyStoreParameter.size() > 0){//es gibt schon Einträge aber nicht den aktuellen
269 inipos = NebraskaMain.keyStoreParameter.size()+1;
270 dummy.add(this.zertantrag.therapidir+"/keystore/"+this.ik+"/"+this.ik+".p12");
271 dummy.add(pw.getText());
272 dummy.add("IK"+this.ik);
273 dummy.add("abc");
274 NebraskaMain.keyStoreParameter.add((Vector<String>) dummy.clone());
275 }else if(!neuerEintrag && eintragBei > 0){
276 inipos = Integer.valueOf(eintragBei);
277 dummy.add(this.zertantrag.therapidir+"/keystore/"+this.ik+"/"+this.ik+".p12");
278 dummy.add(pw.getText());
279 dummy.add("IK"+this.ik);
280 dummy.add("abc");
281 NebraskaMain.keyStoreParameter.set(inipos-1,(Vector<String>) dummy.clone() );
283 org.thera_pi.nebraska.gui.utils.Verschluesseln man = org.thera_pi.nebraska.gui.utils.Verschluesseln.getInstance();
284 man.init(org.thera_pi.nebraska.gui.utils.Verschluesseln.getPassword().toCharArray(), man.getSalt(), man.getIterations());
286 ifile.setIntegerProperty("KeyStores", "KeyStoreAnzahl", NebraskaMain.keyStoreParameter.size(),null);
287 ifile.setStringProperty("KeyStores", "KeyStoreFile"+Integer.toString(inipos),this.zertantrag.therapidir+"/keystore/"+this.ik+"/"+this.ik+".p12",null);
288 ifile.setStringProperty("KeyStores", "KeyStorePw"+Integer.toString(inipos),man.encrypt(pw.getText().trim()),null);
289 ifile.setStringProperty("KeyStores", "KeyStoreAlias"+Integer.toString(inipos),"IK"+this.ik,null);
290 ifile.setStringProperty("KeyStores", "KeyStoreKeyPw"+Integer.toString(inipos),man.encrypt("abc"),null);
291 ifile.save();
292 //Jetzt in die Ini-Schreiben
293 JRtaComboBox cmb = this.zertantrag.elternTab.zertExplorer.jcombo;
294 cmb.setDataVectorWithStartElement(NebraskaMain.keyStoreParameter, 2, 2, "./.");
295 cmb.setSelectedVecIndex(2, "IK"+this.ik);
297 private void doFixIt(){
298 if(pw.getText().trim().equals("")){
299 JOptionPane.showMessageDialog(null, "Passwort darf nicht leer sein!");
300 return;
302 mlabs[0].setEnabled(false);
303 mlabs[1].setEnabled(false);
304 buts[1].setEnabled(false);
305 pw.setEditable(false);
306 mlabs[2].setEnabled(true);
307 buts[2].setEnabled(true);
310 private void doGenerateKeys(){
311 mlabs[2].setEnabled(false);
312 buts[2].setEnabled(false);
313 mlabs[3].setEnabled(true);
314 buts[3].setEnabled(true);
315 String privkeyfile = "privkey"+DatFunk.sDatInSQL(DatFunk.sHeute()).replace("-", "");
316 if(pw.getText().trim().length() > 6){
317 JOptionPane.showMessageDialog(null, "Also wer nicht bis auf 6 zählen kann, der sollte tunlichst die Finger von der Verschlüsselung lassen....");
318 return;
320 try {
321 System.out.println(this.ik);
322 System.out.println(this.institution);
323 keystore = new NebraskaKeystore(
324 this.pathtokeystoredir+File.separator+this.ik+".p12",
325 pw.getText().trim(),
327 this.ik,
328 this.institution,
329 this.person);
330 X509Certificate keyCert = keystore.getKeyCert();
331 if(keyCert != null){
332 String[] teile = keyCert.getSubjectDN().toString().split(",");
333 for(int i = 0; i < teile.length;i++){
334 if(teile[i].equals("OU=IK"+this.ik)){
335 int antwort = JOptionPane.showConfirmDialog(null,"Dieser Schlüssel existiert bereits, wollen Sie einen neuen Schlüssel beantragen?","Achtung extrem wichtige Benutzeranfrage", JOptionPane.YES_NO_OPTION);
336 if(antwort == JOptionPane.YES_OPTION){
337 keystore = new NebraskaKeystore(
338 this.pathtokeystoredir+File.separator+this.ik+"_neu.p12",
339 pw.getText().trim(),
341 this.ik,
342 this.institution,
343 this.person);
344 }else{
345 JOptionPane.showMessageDialog(null,"Der Keystore kann nicht verändert werden");
346 this.dispose();
347 return;
353 keystore.set256Algorithm(true);
354 keystore.generateKeyPairAndSaveToFile(true, privkeyfile, pathtoprivkeydir);
355 //keystore.generateKeyPairAndSaveToFile(false, privkeyfile, pathtoprivkeydir);
356 } catch (NebraskaCryptoException e) {
357 JOptionPane.showMessageDialog(null, "Fehler, es existiert bereits ein gültiges Schlüsselpaar, überschreiben ist nicht erlaubt!"+
358 "\nWenn Sie ein neues Schlüsselpaar erzeugen wollen löschen Sie alle Dateien im Verzeichnis "+this.pathtokeystoredir);
359 e.printStackTrace();
360 } catch (NebraskaFileException e) {
361 e.printStackTrace();
362 } catch (NebraskaNotInitializedException e) {
363 e.printStackTrace();
366 private void doGenerateRequest(){
367 mlabs[3].setEnabled(false);
368 buts[3].setEnabled(false);
369 Nebraska.hmZertifikat.clear();
370 StringBuffer md5Buf = new StringBuffer();
371 try {
372 OutputStream out = new FileOutputStream(this.pathtokeystoredir+File.separator+this.ik+".p10");
373 keystore.createCertificateRequest(out, md5Buf);
374 out.flush();
375 out.close();
377 Nebraska.hmZertifikat.put("<Ikpraxis>","IK"+keystore.getIK());
378 Nebraska.hmZertifikat.put("<Issuerc>","C=DE");
379 Nebraska.hmZertifikat.put("<Issuero>","O="+NebraskaConstants.X500_PRINCIPAL_ORGANIZATION);
380 Nebraska.hmZertifikat.put("<Subjectc>","C=DE");
381 Nebraska.hmZertifikat.put("<Subjecto>","O="+NebraskaConstants.X500_PRINCIPAL_ORGANIZATION);
382 Nebraska.hmZertifikat.put("<Subjectou1>","OU="+keystore.getCompanyName());
383 Nebraska.hmZertifikat.put("<Subjectou2>","OU="+"IK"+keystore.getIK());
384 Nebraska.hmZertifikat.put("<Subjectcn>","CN="+keystore.getCEO());
385 Nebraska.hmZertifikat.put("<Algorithm>",NebraskaConstants.KEY_ALGORITHM);
386 //Nebraska.hmZertifikat.put("<Md5publickey>",md5Buf.toString().replace(":", " "));
387 PKCS10CertificationRequest request = keystore.getCertificateRequest();
388 request.verify(request.getPublicKey(),NebraskaConstants.SECURITY_PROVIDER);
389 CertificationRequestInfo info = request.getCertificationRequestInfo();
390 ASN1Set attrib = info.getAttributes();
391 ASN1Object asno = (ASN1Object) info.getDERObject().toASN1Object();
392 ASN1Sequence aseq = ASN1Sequence.getInstance(asno);
393 SubjectPublicKeyInfo spub = null;
394 for(int i = 0; i < aseq.size();i++){
395 System.out.println("Objec Nr."+i+" aus der ASN1-Struktur = "+aseq.getObjectAt(i));
396 if(aseq.getObjectAt(i) instanceof SubjectPublicKeyInfo){
397 spub = (SubjectPublicKeyInfo) aseq.getObjectAt(i);
398 //System.out.println("Public Key des Requests = "+spub.getPublicKeyData());
399 //System.out.println("SHA1-Hash aus dem PubKey des Requests = "+BCStatics2.getSHA1fromByte(spub.getPublicKeyData().getEncoded()));
404 //String sha1 = BCStatics2.getSHA1fromByte(spub.getPublicKeyData().getBytes());
405 String sha1 = BCStatics2.getSHA256fromByte(spub.getPublicKeyData().getBytes());
406 Nebraska.hmZertifikat.put("<Sha1publickey>",BCStatics2.macheHexDump(sha1, 20," "));
408 String md5 = BCStatics2.getMD5fromByte(spub.getPublicKeyData().getBytes());
409 Nebraska.hmZertifikat.put("<Md5publickey>",BCStatics2.macheHexDump(md5, 20," "));
413 //sha1 = BCStatics2.getSHA1fromByte(request.getEncoded());
414 sha1 = BCStatics2.getSHA256fromByte(request.getEncoded());
415 Nebraska.hmZertifikat.put("<Sha1certificate>",BCStatics2.macheHexDump(sha1, 20," "));
417 md5 = BCStatics2.getMD5fromByte(request.getEncoded());
418 Nebraska.hmZertifikat.put("<Md5certificate>",BCStatics2.macheHexDump(md5, 20," "));
421 java.security.interfaces.RSAPublicKey pub =
422 (java.security.interfaces.RSAPublicKey)request.getPublicKey();
423 String hexstring = new BigInteger(pub.getModulus().toByteArray()).toString(16);
424 //System.out.println("Hexstring = "+hexstring);
425 String modulus = BCStatics2.macheHexDump(hexstring, 20," ");
426 Nebraska.hmZertifikat.put("<Modulus>",modulus);
428 hexstring = new BigInteger(pub.getPublicExponent().toByteArray()).toString(16);
429 Nebraska.hmZertifikat.put("<Exponent>",(hexstring.length()==5 ? "0"+hexstring : hexstring ));
430 String vorlage = this.zertantrag.therapidir+"/defaults/vorlagen/ZertBegleitzettel-SHA256.ott";
431 File f = new File(vorlage);
432 if(!f.exists()){
433 vorlage = FileStatics.dirChooser(this.zertantrag.therapidir+"/defaults/vorlagen/", "Bitte wählen Sie die Vorlage auswählen (Standard = ZertBegleitzettel-SHA256.ott)");
434 if(! vorlage.equals("")){
435 OOorgTools.starteStandardFormular(vorlage, null);
437 }else{
438 OOorgTools.starteStandardFormular(vorlage, null);
440 System.out.println(md5Buf);
441 } catch (FileNotFoundException e) {
442 e.printStackTrace();
443 } catch (NebraskaCryptoException e) {
444 e.printStackTrace();
445 } catch (NebraskaFileException e) {
446 e.printStackTrace();
447 } catch (NebraskaNotInitializedException e) {
448 e.printStackTrace();
449 } catch (IOException e) {
450 e.printStackTrace();
451 } catch (Exception e) {
452 e.printStackTrace();
456 public static void RunAjax(String partUrl,String indatei,String testdatei){
457 InetAddress dieseMaschine = null;
458 try {
459 dieseMaschine = java.net.InetAddress.getLocalHost();
460 } catch (UnknownHostException e1) {
461 e1.printStackTrace();
463 String url = null;
464 if(!dieseMaschine.toString().contains("192.168.2.2")){
465 url = partUrl+"?indatei="+indatei+"&tester="+dieseMaschine.toString()+"&datei="+testdatei;
467 try {
468 URL tester = new URL(url);
469 HttpURLConnection httpURLConnection = (HttpURLConnection) tester.openConnection();
470 httpURLConnection.setAllowUserInteraction(false);
471 httpURLConnection.setRequestMethod("POST");
472 httpURLConnection.getResponseMessage();
473 //System.out.println(httpURLConnection.getResponseMessage());
474 httpURLConnection.setRequestProperty("Accept", "true");
475 httpURLConnection.setDoOutput(true);
476 httpURLConnection.setUseCaches(false);
477 httpURLConnection.disconnect();
478 } catch (MalformedURLException e) {
479 e.printStackTrace();
480 } catch (IOException e) {
481 e.printStackTrace();