Subtrees hinzugefügt

This commit is contained in:
Thomas Schaller 2024-12-29 14:26:34 +01:00
parent e913ca6350
commit 7cf55ce953
53 changed files with 3807 additions and 0 deletions

5
Quellcodes/iud_key_rsachat/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
*.class
*.ctxt
*.sh
repo.adoc
*.~lock

View file

@ -0,0 +1,111 @@
import java.io.ByteArrayOutputStream;
import java.util.Random;
import java.util.Arrays;
import javax.xml.bind.DatatypeConverter;
public class Base64
{
public static String encode(String text)
{
byte[] data = text.getBytes();
return encode(data);
}
public static String encode(byte[] data) {
char[] tbl = {
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' };
StringBuilder buffer = new StringBuilder();
int pad = 0;
for (int i = 0; i < data.length; i += 3) {
int b = ((data[i] & 0xFF) << 16) & 0xFFFFFF;
if (i + 1 < data.length) {
b |= (data[i+1] & 0xFF) << 8;
} else {
pad++;
}
if (i + 2 < data.length) {
b |= (data[i+2] & 0xFF);
} else {
pad++;
}
for (int j = 0; j < 4 - pad; j++) {
int c = (b & 0xFC0000) >> 18;
buffer.append(tbl[c]);
b <<= 6;
}
}
for (int j = 0; j < pad; j++) {
buffer.append("=");
}
return buffer.toString();
}
public static String decodeStr(String data)
{
return new String(decode(data));
}
public static byte[] decode(String data)
{
int[] tbl = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
byte[] bytes = data.getBytes();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
for (int i = 0; i < bytes.length; ) {
int b = 0;
if (tbl[bytes[i]] != -1) {
b = (tbl[bytes[i]] & 0xFF) << 18;
}
// skip unknown characters
else {
i++;
continue;
}
int num = 0;
if (i + 1 < bytes.length && tbl[bytes[i+1]] != -1) {
b = b | ((tbl[bytes[i+1]] & 0xFF) << 12);
num++;
}
if (i + 2 < bytes.length && tbl[bytes[i+2]] != -1) {
b = b | ((tbl[bytes[i+2]] & 0xFF) << 6);
num++;
}
if (i + 3 < bytes.length && tbl[bytes[i+3]] != -1) {
b = b | (tbl[bytes[i+3]] & 0xFF);
num++;
}
while (num > 0) {
int c = (b & 0xFF0000) >> 16;
buffer.write((char)c);
b <<= 8;
num--;
}
i += 4;
}
return buffer.toByteArray();
}
}

Binary file not shown.

View file

@ -0,0 +1,658 @@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.math.BigInteger;
/**
*
* Beschreibung
*
* @version 1.1 vom 30.01.2020
* @author Thomas Schaller
* Version 1.1: Hash-Funkion ausgetauscht, damit Hashes unterschiedlicher. , Ö/P-Schlüssel in der gleichen Farbe
*/
public class ChatClient extends JFrame implements MySocketListener {
//
protected int HOEHE = 60;
// Anfang Attribute
protected JPanel jPanel1 = new JPanel(null, true);
protected JLabel jLabel2 = new JLabel();
protected JTextField jTFName = new JTextField();
protected JTextField jTFAdress = new JTextField();
protected JLabel jLabel3 = new JLabel();
protected JButton jBVerbinden = new JButton();
protected JLabel jLabel1 = new JLabel();
protected JNumberField jNFPort = new JNumberField();
protected JTextField jTFNachricht = new JTextField();
protected MySocket client = null;
protected JLabel jLabel5 = new JLabel();
protected JScrollPane jScrollPane1 = new JScrollPane();
protected JScrollPane jScrollPane2 = new JScrollPane();
protected JPanel jp;
protected ArrayList<Nachricht> nachrichten;
protected ArrayList<Key> keys;
protected ArrayList<String> kontakte;
protected Key dragKey = null;
protected JLabel jLabel4 = new JLabel();
protected GridBagLayout gbl;
protected int keyColor = 0;
private JLabel jLabel6 = new JLabel();
// Ende Attribute
public ChatClient(String title) {
// Frame-Initialisierung
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new WindowListener() {
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
if (client != null) {
client.sendeNachricht("exit");
client.trenneVerbindung();
} // end of if
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
});
int frameWidth = 1081;
int frameHeight = 683;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jPanel1.setBounds(8, 8, 1041, 41);
jPanel1.setOpaque(false);
jPanel1.setBorder(BorderFactory.createBevelBorder(1, Color.WHITE, Color.DARK_GRAY));
cp.add(jPanel1);
jLabel2.setBounds(264, 11, 62, 20);
jLabel2.setText("Server");
jPanel1.add(jLabel2);
jTFName.setBounds(80, 11, 150, 20);
jTFName.setText("anonymous");
jPanel1.add(jTFName);
jTFAdress.setBounds(312, 11, 150, 20);
jTFAdress.setText("localhost");
jPanel1.add(jTFAdress);
jLabel3.setBounds(496, 11, 62, 20);
jLabel3.setText("Port");
jPanel1.add(jLabel3);
jBVerbinden.setBounds(936, 8, 99, 25);
jBVerbinden.setText("Verbinden");
jBVerbinden.setMargin(new Insets(2, 2, 2, 2));
jBVerbinden.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jBVerbinden_ActionPerformed(evt);
}
});
jPanel1.add(jBVerbinden);
jLabel1.setBounds(8, 12, 62, 18);
jLabel1.setText("Name");
jPanel1.add(jLabel1);
jNFPort.setBounds(528, 11, 75, 20);
jNFPort.setText("44444");
jPanel1.add(jNFPort);
jLabel5.setBounds(8, 64, 62, 20);
jLabel5.setText("Schlüssel");
cp.add(jLabel5);
keys = new ArrayList<Key>();
JPanel jp2 = new PicPanel(keys);
jp2.setToolTipText("");
jScrollPane2 = new JScrollPane(jp2);
jScrollPane2.setBounds(96, 64, 953, 57);
jp2.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
keyCached(evt);
}
public void mouseReleased(MouseEvent evt) {
keyDropped(evt);
}
});
cp.add(jScrollPane2);
jLabel4.setBounds(8, 144, 86, 20);
jLabel4.setText("Nachrichten");
cp.add(jLabel4);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
ChatClient_WindowClosing(evt);
}
});
jLabel6.setBounds(816, 624, 229, 20);
jLabel6.setText("(cc) 2020, Thomas Schaller, Version 1.1");
jLabel6.setForeground(Color.GRAY);
cp.add(jLabel6);
// Ende Komponenten
jTFNachricht.setBounds(10, 20, 358, 20);
jTFNachricht.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jTFNachricht_ActionPerformed(evt);
}
});
Random ran = new Random();
nachrichten = new ArrayList<Nachricht>();
kontakte = new ArrayList<String>();
kontakte.add("alle");
jp = new JPanel();
jScrollPane1 = new JScrollPane(jp);
jScrollPane1.setBounds(96, 136, 953, 481);
jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jp.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
keyMessageCached(evt);
}
public void mouseReleased(MouseEvent evt) {
keyMessageDropped(evt);
}
});
cp.add(jScrollPane1);
gbl = new GridBagLayout();
jp.setLayout(gbl);
this.updateNachrichtenListe();
setVisible(true);
} // end of public ChatClient
// Anfang Methoden
public void jBVerbinden_ActionPerformed(ActionEvent evt) {
String a = jTFAdress.getText();
int p = jNFPort.getInt();
if (client != null && client.isAktiv()) {
jTFName.setEnabled(true);
jTFAdress.setEnabled(true);
jNFPort.setEnabled(true);
jBVerbinden.setText("Verbinden");
client.sendeNachricht("exit");
client.trenneVerbindung();
} else {
client = new MySocket(a, p, this);
if (client.isAktiv()) {
jTFName.setEnabled(false);
jTFAdress.setEnabled(false);
jNFPort.setEnabled(false);
jBVerbinden.setText("Trennen");
client.sendeNachricht(("user:"+jTFName.getText()+":alle"));
}
} // end of if-else
} // end of jBVerbinden_ActionPerformed
public byte[] appendOther(byte[] a1, byte[] a2){
byte[] a3 = new byte[a1.length + a2.length];
System.arraycopy(a1, 0, a3, 0, a1.length);
System.arraycopy(a2, 0, a3, a1.length, a2.length);
return a3;
}
public void jBSend_ActionPerformed(ActionEvent evt) {
if (client != null && client.isAktiv()) {
JMyButton button = (JMyButton) evt.getSource();
Nachricht n = button.getNachricht();
n.setEmpfaenger((String) button.getEmpfaenger().getSelectedItem());
String b = "mess:"+n.getAbsender()+":"+n.getEmpfaenger()+":"+Base64.encode(n.getInhalt())+":"+Base64.encode(n.getHashCode());
client.sendeNachricht(b);
this.updateNachrichtenListe();
} else {
jTFName.setEnabled(true);
jTFAdress.setEnabled(true);
jNFPort.setEnabled(true);
jBVerbinden.setEnabled(true);
} // end of if
} // end of jBSend_ActionPerformed
public void generateKeyPair(int bits) {
RSA rsa = new RSA(bits);
rsa.generateKey();
int c = keyColor;
addKey(rsa.getPublicKey());
keyColor = c;
addKey(rsa.getPrivateKey());
}
public void addKey(Key k) {
boolean schonda = false;
for (Key kk : keys) {
if (kk.getN().equals(k.getN()) && kk.getE().equals(k.getE())) {
JOptionPane.showMessageDialog(this,
"Dieser Schlüssel entspricht dem schon vorhandenen Schlüssel "+kk.getName(),
"Achtung",
JOptionPane.WARNING_MESSAGE);
break;
} // end of if
} // end of for
k.setImage("key"+keyColor);
keyColor = (keyColor+1)%10;
keys.add(k);
jScrollPane2.repaint();
}
public void showPublicZertKey() {
Key k = RSA.getPublicKeyZert();
addKey(k);
}
public void signKey(Key k) {
Key nk = new Key(k.getName()+"(z)",k.getE(),k.getN());
nk.sign(RSA.getPrivateKeyZert(),jTFName.getText());
nk.setImage(k.getFilename()+"s");
keys.add(keys.indexOf(k)+1,nk);
jScrollPane2.repaint();
}
public void deleteKey(Key k) {
keys.remove(k);
jScrollPane2.repaint();
}
public void neuerClient(MySocket client) {
}
public void nachrichtEmpfangen(MySocket client) {
String s = client.holeNachricht();
String[] ss = s.split(":");
if (ss[0].equals("user")) {
kontakte.add(ss[1]);
Nachricht n = new Nachricht("Server","alle","Neuer User: "+ss[1]);
n.setSended(true);
nachrichten.add(0,n);
this.updateNachrichtenListe();
}
if(ss[0].equals("mess")) {
String hash;
if (ss.length==5) {
hash = ss[4];
} else {
hash = "";
}// end of if
Nachricht n = new Nachricht(ss[1],ss[2],Base64.decode(ss[3]),Base64.decode(hash));
nachrichten.add(0,n);
this.updateNachrichtenListe();
} // end of if
}
public void verbindungBeendet(MySocket client) {
jTFName.setEnabled(true);
jTFAdress.setEnabled(true);
jNFPort.setEnabled(true);
jBVerbinden.setText("Verbinden");
client = null;
}
public void jTFNachricht_ActionPerformed(ActionEvent evt) {
Nachricht n = new Nachricht(jTFName.getText(),"", jTFNachricht.getText());
jTFNachricht.setText("");
nachrichten.add(0,n);
this.updateNachrichtenListe();
jTFNachricht.requestFocus();
} // end of jTFNachricht_ActionPerformed
public void keyCached(MouseEvent evt) {
Key k = null;
if (evt.getX()>10 && evt.getX()< keys.size()*32+10) {
int k_nr = (int) ((evt.getX()-10) /32);
k = keys.get(k_nr);
}
if (evt.getButton() == evt.BUTTON1) {
if (k != null) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
dragKey = k;
Cursor c = toolkit.createCustomCursor(dragKey.getImage() , new Point(0, 0), "img");
setCursor (c);
}
} else {
new KeyPopup(evt,this, k);
} // end of if
}
public void keyDropped(MouseEvent evt) {
GridBagConstraints c = new GridBagConstraints();
Point p = evt.getPoint();
Point pp = SwingUtilities.convertPoint(jScrollPane2, p, jScrollPane2.getParent());
Point pp2 = SwingUtilities.convertPoint(jScrollPane2, p, jScrollPane1);
if (pp2.getY()>0 && pp2.getY() < jScrollPane1.getHeight() && pp2.getX()>=0 && pp2.getX() < jScrollPane1.getWidth() && dragKey!=null) {
Point ppp = SwingUtilities.convertPoint(jScrollPane2, p, jp);
Component cc = jp.getComponentAt(ppp.x,ppp.y);
GridBagLayout gbl = (GridBagLayout) jp.getLayout();
c = gbl.getConstraints(cc);
int n_nr = c.gridy-1;
if (n_nr == -1) {
Nachricht n;
if (dragKey.isSigned()) {
n = new Nachricht(jTFName.getText(),"",dragKey.toString(jTFName.getText()).getBytes(),dragKey.getHashCode());
} else {
n = new Nachricht(jTFName.getText(),"",dragKey.toString(jTFName.getText()));
} // end of if-else
nachrichten.add(0,n);
this.updateNachrichtenListe();
}
if (n_nr >= 0 && n_nr < nachrichten.size() && c.gridx==1) {
byte[] klar = nachrichten.get(n_nr).getInhalt();
if (dragKey.calcBlocksize()<klar.length) {
JOptionPane.showMessageDialog(this,
"Die Nachricht ist zu lang für diesen Schlüssel. Es können nur "+dragKey.calcBlocksize()+" Zeichen verschlüsselt werden.",
"Fehler",
JOptionPane.WARNING_MESSAGE);
} else {
// end of if
byte[] krypt = dragKey.encrypt(klar);
Nachricht n = nachrichten.get(n_nr).copy();
n.setInhalt(krypt);
n.addKey(dragKey);
nachrichten.add(n_nr+1,n);
this.updateNachrichtenListe();
}
}
if (n_nr >= 0 && n_nr < nachrichten.size() && c.gridx==2) {
byte[] klar = nachrichten.get(n_nr).getHashCode();
if (dragKey.calcBlocksize()<klar.length) {
JOptionPane.showMessageDialog(this,
"Der Schlüssel ist zu kurz für diesen Hashcode. Es können nur "+dragKey.calcBlocksize()+" Zeichen verschlüsselt werden.",
"Fehler",
JOptionPane.WARNING_MESSAGE);
} else {
// end of if
byte[] krypt = dragKey.encrypt(klar);
Nachricht n = nachrichten.get(n_nr).copy();
n.setHashCode(krypt);
n.addHashKey(dragKey);
nachrichten.add(n_nr+1,n);
this.updateNachrichtenListe();
}
}
}
dragKey = null;
Cursor dc = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor (dc);
} // end of jLabel5_MouseClicked
public void keyMessageCached(MouseEvent evt) {
Point p = evt.getPoint();
Point pp = SwingUtilities.convertPoint(jScrollPane1, p, jp);
GridBagLayout gbl = (GridBagLayout) jp.getLayout();
Component cp = jp.getComponentAt(evt.getX(),evt.getY());
GridBagConstraints gbc = gbl.getConstraints(cp);
System.out.println(evt.getY());
if (evt.getButton() == evt.BUTTON1 && gbc.gridx == 1) {
if (gbc.gridy-1< nachrichten.size() && gbc.gridy-1 >= 0) {
int n_nr = gbc.gridy-1;
String[] teile = nachrichten.get(n_nr).getInhaltString().split(",|=");
if (teile[0].equals("Key:Name")) {
BigInteger e = new BigInteger(teile[3]);
BigInteger n = new BigInteger(teile[5]);
dragKey = new Key(teile[1],e,n) ;
dragKey.setImage("key"+keyColor);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Cursor c = toolkit.createCustomCursor(dragKey.getImage() , new Point(0, 0), "img");
setCursor (c);
} // end of if
}
} // end of if
if (evt.getButton() == evt.BUTTON3 && gbc.gridx == 1) {
int n_nr = gbc.gridy-1;
makeMessagePopup(evt,nachrichten.get(n_nr));
} // end of if
}
protected void makeMessagePopup(MouseEvent evt, Nachricht n) {
new MessagePopup(evt, this, n);
}
public void keyMessageDropped(MouseEvent evt) {
Point p = evt.getPoint();
Point pp = SwingUtilities.convertPoint(jp, p, jScrollPane2);
if (pp.getY()>0 && pp.getY() < jScrollPane2.getHeight() && pp.getX()>=0 && pp.getX() < jScrollPane2.getWidth() && dragKey!=null) {
this.addKey(dragKey);
}
dragKey = null;
Cursor dc = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor (dc);
} // end of jLabel5_MouseClicked
public void updateNachrichtenListe() {
//jp.setBounds(jScrollPane1.getViewport().getBounds());
GridBagConstraints c = new GridBagConstraints();
while (jp.getComponentCount()>1) {
jp.remove(1);
} // end of while
//jp.removeAll();
if (jp.getComponentCount()==0) {
JPanel eingabe = new JPanel();
eingabe.setBorder(BorderFactory.createBevelBorder(0));
eingabe.setLayout(null);
eingabe.setBackground(new Color(250,255,200));
eingabe.setOpaque(true);
eingabe.setPreferredSize(new Dimension(150,HOEHE));
c.gridx=0; c.gridy = 0;
c.gridwidth=5;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
jTFNachricht.setBounds(100,20,800,20);
JLabel nn = new JLabel();
nn.setText("Neue Nachricht");
nn.setBounds(2,20,90,20);
eingabe.add(nn);
eingabe.add(jTFNachricht);
jp.add(eingabe,c);
} // end of if
c.weightx=0;
c.gridwidth=1;
int xx = 1;
JLabel name = null;
for (Nachricht n : nachrichten) {
if (n.getKeys().size()>0 && name != null) {
GridBagConstraints c2 = gbl.getConstraints(name);
c2.gridheight++;
gbl.setConstraints(name,c2);
} else {
name = new JLabel();
name.setText("<html>Von "+n.getAbsender()+"</html>");
name.setBorder(BorderFactory.createBevelBorder(0));
name.setBackground(new Color(250,255,200));
name.setOpaque(true);
c.gridx=0; c.gridy = xx;
c.fill = GridBagConstraints.BOTH;
jp.add(name,c);
} // end of if-else
JPanel nnn = new JPanel();
nnn.setLayout(new GridBagLayout());
nnn.setBorder(BorderFactory.createBevelBorder(0));
nnn.setBackground(new Color(250,255,200));
nnn.setOpaque(true);
PicPanel pp = new PicPanel(n.getKeys());
pp.setPreferredSize(new Dimension(n.getKeys().size()*32,HOEHE));
pp.setBackground(new Color(250,255,200));
JMyLabel nachricht = new JMyLabel(n,"");
if (n.getInhaltString().trim().length()>65) {
nachricht.setText("<html>"+n.getInhaltString().trim().substring(0,62)+"...</html>");
} else {
nachricht.setText("<html>"+n.getInhaltString().trim()+"</html>");
} // end of if-else
c.gridx=0; c.gridy = 0;
c.weightx=1.0; c.weighty= 0;
nnn.add(nachricht,c);
c.gridx=1; c.gridy = 0;
c.weightx=0.0; c.weighty= 0;
nnn.add(pp,c);
c.gridx=1; c.gridy = xx;
c.weightx = 1.0;
jp.add(nnn,c);
nnn = new JPanel();
nnn.setLayout(new GridBagLayout());
nnn.setBorder(BorderFactory.createBevelBorder(0));
nnn.setBackground(new Color(250,255,200));
nnn.setOpaque(true);
pp = new PicPanel(n.getHashKeys());
pp.setPreferredSize(new Dimension(n.getHashKeys().size()*32,HOEHE));
pp.setBackground(new Color(250,255,200));
String hc = new String(n.getHashCode());
if (hc.trim().length()>15) {
hc = hc.substring(0,15)+"...";
} //end of if-else
JMyLabel hash = new JMyLabel(n, hc);
c.gridx=0; c.gridy = 0;
c.weightx=1.0; c.weighty= 0;
nnn.add(hash,c);
c.gridx=1; c.gridy = 0;
c.weightx=0.0; c.weighty= 0;
nnn.add(pp,c);
c.gridx=2; c.gridy = xx;
c.weightx = 0.0;
jp.add(nnn,c);
JPanel abspanel = new JPanel();
abspanel.setPreferredSize(new Dimension(150,HOEHE));
abspanel.setBorder(BorderFactory.createBevelBorder(0));
abspanel.setBackground(new Color(250,255,200));
abspanel.setOpaque(true);
abspanel.setLayout(new FlowLayout());
if (n.getEmpfaenger().equals("")) {
String[] stringlist = new String[100];
JComboBox cb = new JComboBox(kontakte.toArray(stringlist));
abspanel.add(cb);
ImageIcon water = new ImageIcon("arrow.png");
JMyButton button = new JMyButton(n, cb, water);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jBSend_ActionPerformed(evt);
}
});
abspanel.add(button);
} else {
abspanel.add(new JLabel("an "+n.getEmpfaenger()));
}
c.gridx=4; c.gridy = xx;
c.weightx = 0.0;
jp.add(abspanel,c);
xx++;
}
JPanel dummy = new JPanel();
dummy.setBorder(BorderFactory.createBevelBorder(0));
dummy.setLayout(null);
dummy.setBackground(new Color(250,255,200));
dummy.setOpaque(true);
dummy.setPreferredSize(new Dimension(150,HOEHE));
c.gridx=0; c.gridy = xx;
c.gridwidth=5;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
jp.add(dummy,c);
jp.revalidate();
jp.repaint();
}
public void ChatClient_WindowClosing(WindowEvent evt) {
// TODO hier Quelltext einfügen
} // end of ChatClient_WindowClosing
// Ende Methoden
public static void main(String[] args) {
new ChatClient("ChatClient");
} // end of main
} // end of class ChatClient

View file

@ -0,0 +1,419 @@
object ChatClient: TFGUIForm
Left = 0
Top = 0
BorderIcons = [biSystemMenu, biMinimize]
Caption = 'ChatClient'
ClientHeight = 644
ClientWidth = 1065
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -10
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsMDIChild
OldCreateOrder = True
Position = poDesigned
ShowHint = True
Visible = True
OnClose = FormClose
OnCloseQuery = FormCloseQuery
OnResize = FormResize
FrameType = 5
Resizable = False
Undecorated = False
Background = clBtnFace
windowClosing = 'ChatClient_WindowClosing'
PixelsPerInch = 96
TextHeight = 13
object jPanel1: TJPanel
Tag = 12
Left = 8
Top = 8
Width = 1041
Height = 41
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Border.BorderType = BevelBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clWhite
Border.BevelShadowColor = 4210752
Border.Beveltype = 1
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
object jLabel2: TJLabel
Tag = 1
Left = 264
Top = 11
Width = 62
Height = 20
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Text = 'Server'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jTFName: TJTextField
Tag = 2
Left = 80
Top = 11
Width = 150
Height = 20
Cursor = crIBeam
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
Foreground = 3355443
Background = clWhite
HorizontalAlignment = LEFT
Text = 'anonymous'
Editable = True
end
object jTFAdress: TJTextField
Tag = 2
Left = 312
Top = 11
Width = 150
Height = 20
Cursor = crIBeam
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
Foreground = 3355443
Background = clWhite
HorizontalAlignment = LEFT
Text = 'localhost'
Editable = True
end
object jLabel3: TJLabel
Tag = 1
Left = 496
Top = 11
Width = 62
Height = 20
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Text = 'Port'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jBVerbinden: TJButton
Tag = 4
Left = 936
Top = 8
Width = 99
Height = 25
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = 15658734
actionPerformed = 'jBVerbinden_ActionPerformed'
Text = 'Verbinden'
Mnemonic = 0
DisplayedMnemonicIndex = 0
Selected = False
BorderPainted = True
FocusPainted = False
ContentAreaFilled = True
HorizontalAlignment = CENTER
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
RolloverEnabled = False
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jLabel1: TJLabel
Tag = 1
Left = 8
Top = 12
Width = 62
Height = 18
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Text = 'Name'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jNFPort: TJNumberField
Tag = 21
Left = 528
Top = 11
Width = 75
Height = 20
Cursor = crIBeam
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
Foreground = 3355443
Background = clWhite
HorizontalAlignment = LEFT
Text = '44444'
Editable = True
end
end
object jTFNachricht: TJTextField
Tag = 2
Left = 672
Top = 320
Width = 358
Height = 20
Cursor = crIBeam
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
Foreground = 3355443
Background = clWhite
actionPerformed = 'jTFNachricht_ActionPerformed'
HorizontalAlignment = LEFT
Editable = True
end
object jBSend: TJButton
Tag = 4
Left = 720
Top = 254
Width = 99
Height = 25
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = 15658734
actionPerformed = 'jBSend_ActionPerformed'
Text = 'Abschicken'
Mnemonic = 0
DisplayedMnemonicIndex = 0
Selected = False
BorderPainted = True
FocusPainted = False
ContentAreaFilled = True
HorizontalAlignment = CENTER
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
RolloverEnabled = False
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jLabel5: TJLabel
Tag = 1
Left = 8
Top = 64
Width = 62
Height = 20
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
mouseClicked = 'jLabel5_MouseClicked'
Text = 'Schl'#252'ssel'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jScrollPane1: TJScrollPane
Tag = 11
Left = 96
Top = 136
Width = 953
Height = 481
Hint = 'jScrollPane1'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = 15658734
HorizontalScrollBarPolicy = AS_NEEDED
VerticalScrollBarPolicy = ALWAYS
Autoscrolls = False
WheelScrollingEnabled = True
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jScrollPane2: TJScrollPane
Tag = 11
Left = 96
Top = 64
Width = 953
Height = 57
Hint = 'jScrollPane2'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = 15658734
HorizontalScrollBarPolicy = AS_NEEDED
VerticalScrollBarPolicy = AS_NEEDED
Autoscrolls = False
WheelScrollingEnabled = True
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jLabel4: TJLabel
Tag = 1
Left = 8
Top = 144
Width = 86
Height = 20
Hint = 'jLabel4'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Text = 'Nachrichten'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jLabel6: TJLabel
Tag = 1
Left = 816
Top = 624
Width = 229
Height = 20
Hint = 'jLabel3'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = clGray
Background = clBtnFace
Text = '(cc) 2017, Thomas Schaller, Version 1.0'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
end

Binary file not shown.

View file

@ -0,0 +1,262 @@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
/**
*
* Beschreibung
*
* @version 1.0 vom 26.05.2017
* @author
*/
public class ChatServerGUI extends JFrame implements MyServerSocketListener {
// Anfang Attribute
private ArrayList<MySocket> clients;
private ArrayList<String> names;
private static boolean ende;
private MyServer server;
private JLabel jLabel1 = new JLabel();
private JButton jBStarten = new JButton();
private JNumberField jNFPort = new JNumberField();
private JList jList1 = new JList();
private DefaultListModel jList1Model = new DefaultListModel();
private JScrollPane jList1ScrollPane = new JScrollPane(jList1);
private JLabel jLabel2 = new JLabel();
private int changeClientListAktiv = 0;
private JLabel jLabel3 = new JLabel();
// Ende Attribute
public ChatServerGUI() {
// Frame-Initialisierung
super();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 300;
int frameHeight = 311;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("Chat-Server");
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jLabel1.setBounds(8, 16, 110, 20);
jLabel1.setText("Portnummer");
cp.add(jLabel1);
jBStarten.setBounds(96, 48, 75, 25);
jBStarten.setText("Starten");
jBStarten.setMargin(new Insets(2, 2, 2, 2));
jBStarten.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jBStarten_ActionPerformed(evt);
}
});
cp.add(jBStarten);
jNFPort.setBounds(128, 16, 99, 20);
jNFPort.setText("44444");
cp.add(jNFPort);
jList1.setModel(jList1Model);
jList1ScrollPane.setBounds(8, 112, 265, 137);
cp.add(jList1ScrollPane);
jLabel2.setBounds(8, 88, 110, 20);
jLabel2.setText("Chatteilnehmer");
cp.add(jLabel2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
ChatServerGUI_WindowClosing(evt);
}
});
jLabel3.setBounds(24, 248, 229, 20);
jLabel3.setText("(cc) 2017, Thomas Schaller, Version 1.0");
jLabel3.setForeground(Color.GRAY);
cp.add(jLabel3);
// Ende Komponenten
setVisible(true);
clients = new ArrayList<MySocket>();
names = new ArrayList<String>();
server = null;
} // end of public ChatServerGUI
// Anfang Methoden
public void neuerClient(MySocket client) {
for (String n : names) {
if (!n.equals("ManInTheMiddle")) {
client.sendeNachricht("user:"+n);
} // end of if
} // end of for
this.clients.add(client);
// System.out.println("Habe Kontakt mit "+client.getSocket().getInetAddress()+" Port "+client.getSocket().getPort());
this.names.add("?");
// changeClientList();
}
public void changeClientList() {
changeClientListAktiv++;
if (changeClientListAktiv == 1) {
do{
changeClientListAktiv--;
DefaultListModel newListModel = new DefaultListModel();
System.out.println("lm: "+jList1Model.size());
System.out.println("Clients: "+clients.size());
for (int i = 0; i < clients.size() ; i++ ) {
MySocket s = clients.get(i);
String n = names.get(i);
newListModel.addElement(n+"("+s.getSocket().getInetAddress()+":"+s.getSocket().getPort()+")");
System.out.println(n+"("+s.getSocket().getInetAddress()+":"+s.getSocket().getPort()+")");
System.out.println("lm: "+jList1Model.size());
} // end of for
jList1.setModel(newListModel);
jList1.validate();
}
while (changeClientListAktiv > 0 );
} // end of if
}
public void nachrichtEmpfangen(MySocket client) {
String s = client.holeNachricht();
System.out.println("Habe Nachricht empfangen:"+s);
String[] ss = s.split(":");
int i = clients.indexOf(client);
if (ss[0].equals("exit")) {
s = s+names.get(i);
clients.remove(i);
names.remove(i);
client.trenneVerbindung();
for (int j=0; j<clients.size(); j++) {
MySocket c = clients.get(j);
if (c!=client) {
c.sendeNachricht(s);
} // end of if
}
changeClientList();
return;
}
if (ss[0].equals("user")) {
names.set(i,ss[1]);
for (int j=0; j<clients.size(); j++) {
MySocket c = clients.get(j);
if (c!=client) {
c.sendeNachricht(s);
} // end of if
}
changeClientList();
return;
}
if (ss[0].equals("mitm")) {
names.set(i,"ManInTheMiddle");
changeClientList();
return;
}
if (ss[0].equals("mess")) {
int nextMitM=-1;
int start=0;
if (names.get(i).equals("ManInTheMiddle")) {
start = i+1;
}
for (int j=start;j<clients.size() ;j++ ) {
if (names.get(j).equals("ManInTheMiddle")) {
nextMitM = j;
break;
} // end of if
} // end of for
if (nextMitM!=-1) {
MySocket c = clients.get(nextMitM);
c.sendeNachricht(s);
} else {
for (int j=0; j<clients.size(); j++) {
MySocket c = clients.get(j);
if (!ss[1].equals(names.get(j)) && (ss[2].equals("alle") || ss[2].equals(names.get(j))) && !names.get(j).equals("ManInTheMiddle")) {
c.sendeNachricht(s);
} // end of if
}
} // end of if-else
} // end of if
} // end of if
public void verbindungBeendet(MySocket client) {
if (clients.contains(client)) {
int i = clients.indexOf(client);
clients.remove(i);
System.out.println("Verbindung mit "+client.getSocket().getInetAddress()+" Port: "+client.getSocket().getPort()+" verloren.");
for (MySocket c: clients) {
if (c!=client) {
c.sendeNachricht(("exit:"+names.get(i)+":alle"));
} // end of if
}
names.remove(i);
changeClientList();
} // end of if
}
/* public static void main (String[] args) {
new ChatServer(44444);
ende = false;
while (!ende) {
try{
Thread.sleep(100);
}
catch(Exception e) {
System.out.println("Error");
}
} // end of while
}
// Anfang Methoden
*/
public static void main(String[] args) {
new ChatServerGUI();
} // end of main
public void jBStarten_ActionPerformed(ActionEvent evt) {
if (jBStarten.getText().equals("Starten")) {
server = new MyServer(this, this.jNFPort.getInt());
server.starten();
jBStarten.setText("Stoppen");
jNFPort.setEnabled(false);
} else {
server.stoppen();
server = null;
jBStarten.setText("Starten");
jNFPort.setEnabled(true);
} // end of if-else
} // end of jBStarten_ActionPerformed
public void ChatServerGUI_WindowClosing(WindowEvent evt) {
if (server != null) server.stoppen();
} // end of ChatServerGUI_WindowClosing
// Ende Methoden
} // end of class ChatServerGUI

View file

@ -0,0 +1,188 @@
object ChatServerGUI: TFGUIForm
Left = 0
Top = 0
BorderIcons = [biSystemMenu]
Caption = 'Chat-Server'
ClientHeight = 272
ClientWidth = 284
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -10
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsMDIChild
OldCreateOrder = True
Position = poDesigned
ShowHint = True
Visible = True
OnClose = FormClose
OnCloseQuery = FormCloseQuery
OnResize = FormResize
FrameType = 5
Resizable = False
Undecorated = False
Background = clBtnFace
windowClosing = 'ChatServerGUI_WindowClosing'
PixelsPerInch = 96
TextHeight = 13
object jLabel1: TJLabel
Tag = 1
Left = 8
Top = 16
Width = 110
Height = 20
Hint = 'jLabel1'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Text = 'Portnummer'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jBStarten: TJButton
Tag = 4
Left = 96
Top = 48
Width = 75
Height = 25
Hint = 'jButton1'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = 15658734
actionPerformed = 'jBStarten_ActionPerformed'
Text = 'Starten'
Mnemonic = 0
DisplayedMnemonicIndex = 0
Selected = False
BorderPainted = True
FocusPainted = False
ContentAreaFilled = True
HorizontalAlignment = CENTER
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
RolloverEnabled = False
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jNFPort: TJNumberField
Tag = 21
Left = 128
Top = 16
Width = 99
Height = 20
Cursor = crIBeam
Hint = 'jNumberField1'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
Foreground = 3355443
Background = clWhite
HorizontalAlignment = LEFT
Text = '44444'
Editable = True
end
object jList1: TJList
Tag = 8
Left = 8
Top = 112
Width = 265
Height = 137
Hint = 'jList1'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clWhite
SelectionMode = MULTIPLE_INTERVAL
FixedCellHeight = -1
FixedCellWidth = -1
LayoutOrientation = VERTICAL
SelectionBackground = 15060920
SelectionForeground = 3355443
VisibleRowCount = 8
HorizontalScrollBarPolicy = AS_NEEDED
VerticalScrollBarPolicy = AS_NEEDED
SelectedIndex = -1
Items.Strings = (
'')
end
object jLabel2: TJLabel
Tag = 1
Left = 8
Top = 88
Width = 110
Height = 20
Hint = 'jLabel2'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = 3355443
Background = clBtnFace
Text = 'Chatteilnehmer'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jLabel3: TJLabel
Tag = 1
Left = 24
Top = 248
Width = 229
Height = 20
Hint = 'jLabel3'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Foreground = clGray
Background = clBtnFace
Text = '(cc) 2017, Thomas Schaller, Version 1.0'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
end

Binary file not shown.

View file

@ -0,0 +1,38 @@
/**
*
* Beschreibung
*
* @version 1.0 vom 25.01.2016
* @author
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
public class JMyButton extends JButton {
// Anfang Attribute
private Nachricht nachricht;
private JComboBox empfaenger;
// Ende Attribute
public JMyButton(Nachricht nachricht, JComboBox cb, ImageIcon ii) {
super(ii);
this.nachricht = nachricht;
this.empfaenger = cb;
}
// Anfang Methoden
public Nachricht getNachricht() {
return nachricht;
}
public JComboBox getEmpfaenger() {
return empfaenger;
}// Ende Methoden
} // end of JMyLabel

View file

@ -0,0 +1,35 @@
/**
*
* Beschreibung
*
* @version 1.0 vom 25.01.2016
* @author
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
public class JMyLabel extends JLabel {
// Anfang Attribute
private Nachricht nachricht;
// Ende Attribute
public JMyLabel(Nachricht nachricht, String s) {
super();
this.setText(s);
this.nachricht = nachricht;
}
// Anfang Methoden
public Nachricht getNachricht() {
return nachricht;
}
} // end of JMyLabel

View file

@ -0,0 +1,193 @@
/**
*
* description
*
* @version 1.0 from 15.01.2016
* @author
*/
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.*;
import java.awt.FontMetrics;
public class Key {
// Anfang Attribute
private String name;
private BigInteger n;
private BigInteger e;
private int BLOCKSIZE;
private BufferedImage image;
private String filename;
private byte[] hashCode;
// Ende Attribute
public Key(String name, BigInteger e, BigInteger n) {
this.name = name;
this.n = n;
this.e = e;
this.image = image;
this.hashCode = null;
calcBlocksize();
}
// Anfang Methoden
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigInteger getN() {
return n;
}
public BigInteger getE() {
return e;
}
public void setImage(String filename) {
URL pic_url = this.getClass().getClassLoader().getResource(filename+".png"); //kein Slash vor dem Unterordner!
this.filename = filename;
//Bild laden mit ImageIO
try {
image = ImageIO.read(pic_url);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getFilename() {
return filename;
}
public BufferedImage getImage() {
return image;
}
private BigInteger convert(String text) {
BigInteger i = BigInteger.valueOf(0);
for(int j =0; j < text.length(); j++) {
i = i.multiply(BigInteger.valueOf(256));
i = i.add(BigInteger.valueOf((int) text.charAt(j)));
} // end of while
// System.out.println(text+" in "+i.toString()+" umgewandelt.");
return i;
}
public BigInteger convert(byte[] text) {
BigInteger i = BigInteger.valueOf(0);
for(int j =text.length-1; j >=0; j--) {
i = i.multiply(BigInteger.valueOf(256));
int unsingedByte = ((int)text[j]) & 0xFF;
// System.out.println(""+unsingedByte+" ");
i = i.add(BigInteger.valueOf(unsingedByte));
} // end of while
// System.out.println("");
// System.out.println(new String(text)+" in "+i.toString()+" umgewandelt.");
return i;
}
/* private String convert(BigInteger i) {
String text = "";
int j = 0;
while (text.length()<BLOCKSIZE) {
j = i.mod(BigInteger.valueOf(256)).intValue();
i = i.divide(BigInteger.valueOf(256));
text = (char) j+text;
} // end of while
//System.out.println(i.toString()+" in "+text+" umgewandelt.");
return text;
} */
public byte[] convert(BigInteger i) {
byte[] text = new byte[BLOCKSIZE];
int j = 0;
int x = 0;
while (!i.equals(BigInteger.ZERO)) {
j = i.mod(BigInteger.valueOf(256)).intValue();
i = i.divide(BigInteger.valueOf(256));
text[x] = (byte) j;
x++;
} // end of while
//System.out.println(i.toString()+" in "+text+" umgewandelt.");
byte[] a3 = new byte[x];
System.arraycopy(text, 0, a3, 0, x);
return a3;
}
public int calcBlocksize() {
BigInteger bs = BigInteger.valueOf(1);
int size = 1;
while (bs.compareTo(n)<0) {
bs = bs.multiply(BigInteger.valueOf(256));
size++;
}
BLOCKSIZE = size-1;
//System.out.println(size-1);
return BLOCKSIZE;
}
public String encrypt(String text) {
String kr = "";
BigInteger i;
i = convert(text);
i = i.modPow(e, n);
//System.out.println(i);
kr = kr+ convert(i);
return kr;
}
public BigInteger encrypt(BigInteger i) {
i = i.modPow(e, n);
return i;
}
public byte[] encrypt(byte[] text) {
byte[] kr;
BigInteger i;
i = convert(text);
i = i.modPow(e, n);
// System.out.println(i);
kr = convert(i);
return kr;
}
public String toString(String name) {
return "Key:Name="+name+",E="+getE()+",N="+getN();
}
public void sign(Key k, String name) {
Nachricht dummy = new Nachricht("dummy","dummy",toString(name));
dummy.generateHash();
byte[] b = dummy.getHashCode();
hashCode = k.encrypt(b);
}
public boolean isSigned() {
return hashCode!=null;
}
public byte[] getHashCode() {
return hashCode;
}
// Ende Methoden
}

View file

@ -0,0 +1,94 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JOptionPane;
public class KeyPopup extends JPopupMenu implements ActionListener {
private static final long serialVersionUID = 1L;
JMenuItem bmi, ami, emi, kmi, dmi1, dmi2, dmi3, vmi;
ChatClient cc;
Key k;
public KeyPopup( MouseEvent event, ChatClient cc, Key k){
this.cc = cc;
this.k = k;
// Submenu
dmi1 = new JMenuItem("Schlüsselpaar (50bit) erzeugen");
dmi1.addActionListener(this);
add(dmi1);
dmi2 = new JMenuItem("Schlüsselpaar (512bit) erzeugen");
dmi2.addActionListener(this);
add(dmi2);
dmi3 = new JMenuItem("Schlüsselpaar (1024bit) erzeugen");
dmi3.addActionListener(this);
add(dmi3);
addSeparator();
if (k != null) {
vmi = new JMenuItem("Schlüssel-Name-Paar zertifizieren");
vmi.addActionListener(this);
add(vmi);
} // end of if
bmi = new JMenuItem("Öffentlichen Schlüssel der Zertifizierungsstelle anzeigen");
bmi.addActionListener(this);
add(bmi);
addSeparator();
if (k!=null) {
ami = new JMenuItem("Schlüssel löschen");
ami.addActionListener(this);
add(ami);
} // end of if
/*
kmi = new JMenuItem("Schlüssel selbst eingeben");
kmi.addActionListener(this);
add(kmi);
*/
show(event.getComponent(), event.getX(), event.getY());
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == dmi1) {
cc.generateKeyPair(50);
}
if (e.getSource() == dmi2) {
cc.generateKeyPair(512);
}
if (e.getSource() == dmi3) {
cc.generateKeyPair(1024);
}
if (e.getSource()== bmi) {
cc.showPublicZertKey();
} // end of if
if (e.getSource() == vmi) {
JOptionPane.showMessageDialog(this,
"Gehen Sie bitte mit Ihrem Schlüssel zur Zertifizierungsstelle.\nSind Sie angekommen?",
"Zertifizierung",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this,
"Geben Sie dort bitte Ihren Schlüssel ab und weisen Sie sich als "+cc.jTFName.getText()+" aus.\nHaben Sie sich ausgewiesen?",
"Zertifizierung",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this,
"Sie erhalten jetzt von der Zertifizierungsstelle Ihren mit "+cc.jTFName.getText()+" zertifizierten Schlüssel.\nMöchten Sie diesen in Ihrem Chat-Client importieren?",
"Zertifizierung",
JOptionPane.INFORMATION_MESSAGE);
cc.signKey(k);
} // end of if
if (e.getSource() == ami) {
cc.deleteKey(k);
} // end of if
}
}

View file

@ -0,0 +1,5 @@
Manifest-Version: 1.0
Class-Path: JEClasses.jar jdom-1.1.3.jar
Created-By: 1.8.0_111 (Oracle Corporation)
Main-Class: ManInTheMiddle

Binary file not shown.

View file

@ -0,0 +1,355 @@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.math.BigInteger;
/**
*
* Beschreibung
*
*
* @version 1.1 vom 30.01.2020
* @author Thomas Schaller
* Version 1.1: Hash-Funkion ausgetauscht, damit Hashes unterschiedlicher, Ö/P-Schlüssel in der gleichen Farbe
*/
import java.util.Timer;
public class ManInTheMiddle extends ChatClient implements MySocketListener {
// Anfang Attribute
// Ende Attribute
public ManInTheMiddle(String title) {
// Frame-Initialisierung
super(title);
jTFName.setText("ManInTheMiddle");
jTFName.setEnabled(false);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
updateTimes();
}
}, 1000, 1000);
} // end of public ManInTheMiddle
// Anfang Methoden
public void jBVerbinden_ActionPerformed(ActionEvent evt) {
String a = jTFAdress.getText();
int p = jNFPort.getInt();
if (client != null && client.isAktiv()) {
jTFAdress.setEnabled(true);
jNFPort.setEnabled(true);
jBVerbinden.setText("Verbinden");
client.trenneVerbindung();
} else {
client = new MySocket(a, p, this);
if (client.isAktiv()) {
jTFAdress.setEnabled(false);
jNFPort.setEnabled(false);
jBVerbinden.setText("Trennen");
client.sendeNachricht("mitm:");
}
} // end of if-else
} // end of jBVerbinden_ActionPerformed
public void jBSend_ActionPerformed(ActionEvent evt) {
if (client != null && client.isAktiv()) {
JMyButton button = (JMyButton) evt.getSource();
if (button.getEmpfaenger()!=null) {
button.getNachricht().setEmpfaenger((String) button.getEmpfaenger().getSelectedItem());
} // end of if
sendMessage(button.getNachricht());
this.updateNachrichtenListe();
} else {
jTFAdress.setEnabled(true);
jNFPort.setEnabled(true);
jBVerbinden.setEnabled(true);
} // end of if
} // end of jBSend_ActionPerformed
private void sendMessage(Nachricht n) {
String b = "mess:"+n.getAbsender()+":"+n.getEmpfaenger()+":"+Base64.encode(n.getInhalt())+":"+Base64.encode(n.getHashCode());
n.setStopped(false);
n.setSended(true);
client.sendeNachricht(b);
}
public void nachrichtEmpfangen(MySocket client) {
String s = client.holeNachricht();
String[] ss = s.split(":");
if (ss[0].equals("user")) {
kontakte.add(ss[1]);
Nachricht n = new Nachricht("Server","alle","Neuer User: "+ss[1]);
n.setSended(true);
nachrichten.add(0,n);
this.updateNachrichtenListe();
}
if(ss[0].equals("mess")) {
String hash;
if (ss.length==5) {
hash = ss[4];
} else {
hash = "";
}// end of if
Nachricht n = new Nachricht(ss[1],ss[2],Base64.decode(ss[3]),Base64.decode(hash));
nachrichten.add(0,n);
this.updateNachrichtenListe();
} // end of if String s = client.holeNachricht();
}
protected void makeMessagePopup(MouseEvent evt, Nachricht n) {
new MessagePopup2(evt, this, n, keys);
}
public void verbindungBeendet(MySocket client) {
jTFAdress.setEnabled(true);
jNFPort.setEnabled(true);
jBVerbinden.setText("Verbinden");
client = null;
}
public void jBStopped_ActionPerformed(ActionEvent evt) {
JMyButton button = (JMyButton) evt.getSource();
Nachricht n = button.getNachricht();
n.setStopped(true);
} // end of jBSend_ActionPerformed
public void updateTimes() {
int i=0;
Component[] c = jp.getComponents();
int cnr = 0;
for (Nachricht n: nachrichten ) {
if (n.getRestzeit()>0) {
GridBagConstraints c2 = gbl.getConstraints(c[cnr]);
while (cnr < c.length-1 && (c2.gridx != 4 || c2.gridy!=i+1)) {
cnr++;
c2 = gbl.getConstraints(c[cnr]);
} // end of while
JPanel p = (JPanel) (c[cnr]);
if (p.getComponents()[1] instanceof JLabel) {
JLabel l = (JLabel) (p.getComponents()[1]);
l.setText(""+n.getRestzeit()+" sek");
} // end of if
} else {
if (!n.getSended() && !n.getStopped() && !n.getEmpfaenger().equals("")) {
sendMessage(n);
updateNachrichtenListe();
break;
}// end of if-else// end of if
}
i++;
} // end of for
}
public void updateNachrichtenListe() {
GridBagConstraints c = new GridBagConstraints();
while (jp.getComponentCount()>1) {
jp.remove(1);
} // end of while
//jp.removeAll();
if (jp.getComponentCount()==0) {
JPanel eingabe = new JPanel();
eingabe.setBorder(BorderFactory.createBevelBorder(0));
eingabe.setLayout(null);
eingabe.setBackground(new Color(250,255,200));
eingabe.setOpaque(true);
eingabe.setPreferredSize(new Dimension(150,60));
c.gridx=0; c.gridy = 0;
c.gridwidth=5;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
jTFNachricht.setBounds(100,20,800,20);
JLabel nn = new JLabel();
nn.setText("Neue Nachricht");
nn.setBounds(2,20,90,20);
eingabe.add(nn);
eingabe.add(jTFNachricht);
jp.add(eingabe,c);
}
c.weightx=0;
c.gridwidth=1;
int xx = 1;
JLabel name = null;
for (Nachricht n : nachrichten) {
if (n.getKeys().size()>0 && name != null) {
GridBagConstraints c2 = gbl.getConstraints(name);
c2.gridheight++;
gbl.setConstraints(name,c2);
} else {
name = new JLabel();
name.setText("<html>Von "+n.getAbsender()+"</html>");
name.setBorder(BorderFactory.createBevelBorder(0));
name.setBackground(new Color(250,255,200));
name.setOpaque(true);
c.gridx=0; c.gridy = xx;
c.fill = GridBagConstraints.BOTH;
jp.add(name,c);
} // end of if-else
JPanel nnn = new JPanel();
nnn.setLayout(new GridBagLayout());
nnn.setBorder(BorderFactory.createBevelBorder(0));
nnn.setBackground(new Color(250,255,200));
nnn.setOpaque(true);
PicPanel pp = new PicPanel(n.getKeys());
pp.setPreferredSize(new Dimension(n.getKeys().size()*32,60));
pp.setBackground(new Color(250,255,200));
JMyLabel nachricht = new JMyLabel(n,"");
if (n.getInhaltString().trim().length()>65) {
nachricht.setText("<html>"+n.getInhaltString().trim().substring(0,62)+"...</html>");
} else {
nachricht.setText("<html>"+n.getInhaltString().trim()+"</html>");
} // end of if-else
c.gridx=0; c.gridy = 0;
c.weightx=1.0; c.weighty= 0;
nnn.add(nachricht,c);
c.gridx=1; c.gridy = 0;
c.weightx=0.0; c.weighty= 0;
nnn.add(pp,c);
c.gridx=1; c.gridy = xx;
c.weightx = 1.0;
jp.add(nnn,c);
nnn = new JPanel();
nnn.setLayout(new GridBagLayout());
nnn.setBorder(BorderFactory.createBevelBorder(0));
nnn.setBackground(new Color(250,255,200));
nnn.setOpaque(true);
pp = new PicPanel(n.getHashKeys());
pp.setPreferredSize(new Dimension(n.getHashKeys().size()*32,60));
pp.setBackground(new Color(250,255,200));
String hc = new String(n.getHashCode());
if (hc.trim().length()>15) {
hc = hc.substring(0,15)+"...";
} //end of if-else
JMyLabel hash = new JMyLabel(n, hc);
c.gridx=0; c.gridy = 0;
c.weightx=1.0; c.weighty= 0;
nnn.add(hash,c);
c.gridx=1; c.gridy = 0;
c.weightx=0.0; c.weighty= 0;
nnn.add(pp,c);
c.gridx=2; c.gridy = xx;
c.weightx = 0.0;
jp.add(nnn,c);
JPanel abspanel = new JPanel();
abspanel.setPreferredSize(new Dimension(150,40));
abspanel.setBorder(BorderFactory.createBevelBorder(0));
abspanel.setBackground(new Color(250,255,200));
abspanel.setOpaque(true);
abspanel.setLayout(new FlowLayout());
if (n.getEmpfaenger().equals("") && n.getSended()==false ) {
String[] stringlist = new String[100];
JComboBox cb = new JComboBox(kontakte.toArray(stringlist));
abspanel.add(cb);
ImageIcon water = new ImageIcon("arrow.png");
JMyButton button = new JMyButton(n, cb, water);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jBSend_ActionPerformed(evt);
}
});
abspanel.add(button);
} else {
abspanel.add(new JLabel("an "+n.getEmpfaenger()));
if (n.getStopped() && n.getSended()==false) {
ImageIcon water = new ImageIcon("arrow.png");
JMyButton button = new JMyButton(n,null,water);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jBSend_ActionPerformed(evt);
}
});
abspanel.add(button);
} else {
if (n.getRestzeit()>0) {
abspanel.add(new JLabel(" "+n.getRestzeit()+" sek"));
ImageIcon water = new ImageIcon("stop.png");
JMyButton button = new JMyButton(n,null,water);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jBStopped_ActionPerformed(evt);
}
});
abspanel.add(button);
} // end of if
}
}
c.gridx=4; c.gridy = xx;
c.weightx = 0.0;
jp.add(abspanel,c);
xx++;
}
JPanel dummy = new JPanel();
dummy.setBorder(BorderFactory.createBevelBorder(0));
dummy.setLayout(null);
dummy.setBackground(new Color(250,255,200));
dummy.setOpaque(true);
dummy.setPreferredSize(new Dimension(150,60));
c.gridx=0; c.gridy = xx;
c.gridwidth=5;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
jp.add(dummy,c);
jp.revalidate();
jp.repaint();
}
// Ende Methoden
public static void main(String[] args) {
new ManInTheMiddle("ManInTheMiddle");
} // end of main
} // end of class ManInTheMiddle

View file

@ -0,0 +1,355 @@
object chatClient: TFGUIForm
Left = 332
Top = 16
BorderIcons = [biSystemMenu, biMinimize]
Caption = 'I:\PublicKey\PublicKey\ManInTheMiddle.jfm'
ClientHeight = 626
ClientWidth = 1065
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -10
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsMDIChild
OldCreateOrder = True
Position = poDesigned
ShowHint = True
Visible = True
OnClose = FormClose
OnCloseQuery = FormCloseQuery
OnResize = FormResize
FrameType = 5
Resizable = False
Undecorated = False
Background = clBtnFace
PixelsPerInch = 96
TextHeight = 13
object jPanel1: TJPanel
Tag = 12
Left = 8
Top = 8
Width = 1041
Height = 41
Foreground = 3355443
Background = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Border.BorderType = BevelBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clWhite
Border.BevelShadowColor = 4210752
Border.Beveltype = 1
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
object jLabel2: TJLabel
Tag = 1
Left = 8
Top = 11
Width = 62
Height = 20
Foreground = 3355443
Background = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Text = 'Server'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jTFAdress: TJTextField
Tag = 2
Left = 56
Top = 11
Width = 150
Height = 20
Cursor = crIBeam
Foreground = 3355443
Background = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
HorizontalAlignment = LEFT
Text = 'localhost'
Editable = True
end
object jLabel3: TJLabel
Tag = 1
Left = 232
Top = 11
Width = 62
Height = 20
Foreground = 3355443
Background = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Text = 'Port'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jBVerbinden: TJButton
Tag = 4
Left = 936
Top = 8
Width = 99
Height = 25
Foreground = 3355443
Background = 15658734
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
actionPerformed = 'jBVerbinden_ActionPerformed'
Text = 'Verbinden'
Mnemonic = 0
DisplayedMnemonicIndex = 0
Selected = False
BorderPainted = True
FocusPainted = False
ContentAreaFilled = True
HorizontalAlignment = CENTER
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
RolloverEnabled = False
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jNFPort: TJNumberField
Tag = 21
Left = 272
Top = 11
Width = 75
Height = 20
Cursor = crIBeam
Foreground = 3355443
Background = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
HorizontalAlignment = LEFT
Text = '44444'
Editable = True
end
end
object jTFNachricht: TJTextField
Tag = 2
Left = 672
Top = 320
Width = 358
Height = 20
Cursor = crIBeam
Foreground = 3355443
Background = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = []
actionPerformed = 'jTFNachricht_ActionPerformed'
HorizontalAlignment = LEFT
Editable = True
end
object jBSend: TJButton
Tag = 4
Left = 720
Top = 254
Width = 99
Height = 25
Foreground = 3355443
Background = 15658734
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
actionPerformed = 'jBSend_ActionPerformed'
Text = 'Abschicken'
Mnemonic = 0
DisplayedMnemonicIndex = 0
Selected = False
BorderPainted = True
FocusPainted = False
ContentAreaFilled = True
HorizontalAlignment = CENTER
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
RolloverEnabled = False
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jLabel5: TJLabel
Tag = 1
Left = 8
Top = 64
Width = 62
Height = 20
Foreground = 3355443
Background = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
mouseClicked = 'jLabel5_MouseClicked'
Text = 'Schl'#252'ssel'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
object jScrollPane1: TJScrollPane
Tag = 11
Left = 96
Top = 136
Width = 953
Height = 481
Hint = 'jScrollPane1'
Foreground = 3355443
Background = 15658734
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
HorizontalScrollBarPolicy = AS_NEEDED
VerticalScrollBarPolicy = ALWAYS
Autoscrolls = False
WheelScrollingEnabled = True
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jScrollPane2: TJScrollPane
Tag = 11
Left = 96
Top = 64
Width = 953
Height = 57
Hint = 'jScrollPane2'
Foreground = 3355443
Background = 15658734
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
HorizontalScrollBarPolicy = AS_NEEDED
VerticalScrollBarPolicy = AS_NEEDED
Autoscrolls = False
WheelScrollingEnabled = True
Border.BorderType = NoBorder
Border.LineColor = clBlack
Border.LineThickness = 0
Border.LineRounded = False
Border.EtchHighlightColor = clBlack
Border.EtchShadowColor = clBlack
Border.Etchtype = 0
Border.BevelHighlightColor = clBlack
Border.BevelShadowColor = clBlack
Border.Beveltype = 0
Border.MatteColor = clBlack
Border.MatteTop = 0
Border.MatteLeft = 0
Border.MatteBottom = 0
Border.MatteRight = 0
end
object jLabel4: TJLabel
Tag = 1
Left = 8
Top = 144
Width = 86
Height = 20
Hint = 'jLabel4'
Foreground = 3355443
Background = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Dialog'
Font.Style = [fsBold]
Text = 'Nachrichten'
HorizontalAlignment = LEFT
VerticalAlignment = CENTER
HorizontalTextPosition = RIGHT
VerticalTextPosition = CENTER
IconTextGap = 4
DisplayedMnemonic = 0
DisplayedMnemonicIndex = 0
end
end

View file

@ -0,0 +1,59 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.*;
public class MessagePopup extends JPopupMenu implements ActionListener {
private static final long serialVersionUID = 1L;
JMenuItem bmi, ami, emi, kmi, dmi1, dmi2, dmi3, vmi;
ChatClient cc;
Nachricht n;
public MessagePopup( MouseEvent event, ChatClient cc, Nachricht n){
this.cc = cc;
this.n = n;
// Submenu
dmi1 = new JMenuItem("Hashcode berechnen");
dmi1.addActionListener(this);
add(dmi1);
dmi2 = new JMenuItem("Hashcode prüfen");
dmi2.addActionListener(this);
add(dmi2);
show(event.getComponent(), event.getX(), event.getY());
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == dmi1) {
n.generateHash();
cc.updateNachrichtenListe();
}
if (e.getSource() == dmi2) {
Nachricht dummy = new Nachricht("dummy","dummy",n.getInhaltString());
dummy.generateHash();
String ha2 = new String(dummy.getHashCode());
String ha = new String(n.getHashCode());
System.out.println(ha2+","+ha);
if(ha.equals(ha2)) {
JOptionPane.showMessageDialog(this,
"Der Hashcode der Nachricht stimmt mit dem übermittelten Hashcode überein",
"Bestätigung",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this,
"Der Hashcode der Nachricht passt nicht zum übermittelten Hashcode.",
"Fehler",
JOptionPane.ERROR_MESSAGE);
}
}
}
}

View file

@ -0,0 +1,128 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.*;
import java.util.*;
public class MessagePopup2 extends JPopupMenu implements ActionListener {
private static final long serialVersionUID = 1L;
JMenuItem bmi, ami, emi, kmi, dmi1, dmi2, dmi3, vmi;
ChatClient cc;
Nachricht n;
ArrayList<Key> keys;
public MessagePopup2( MouseEvent event, ChatClient cc, Nachricht n, ArrayList<Key> keys){
this.cc = cc;
this.n = n;
this.keys = keys;
// Submenu
if (!n.getSended() && n.getInhaltString().startsWith("Key:")) {
ami = new JMenuItem("Schlüssel austauschen");
ami.addActionListener(this);
add(ami);
} // end of if
if (!n.getSended()) {
emi = new JMenuItem("Nachricht verändern");
emi.addActionListener(this);
add(emi);
this.addSeparator();
} // end of if
dmi1 = new JMenuItem("Hashcode berechnen");
dmi1.addActionListener(this);
add(dmi1);
dmi2 = new JMenuItem("Hashcode prüfen");
dmi2.addActionListener(this);
add(dmi2);
show(event.getComponent(), event.getX(), event.getY());
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == ami && !n.getSended()) {
n.setStopped(true);
JComboBox cb = new JComboBox();
for(Key k: keys) {
cb.addItem(k.getName());
} // end of for
Object[] message = {"Wähle den Schlüssel, der eingesetzt werden soll.", cb};
JOptionPane pane = new JOptionPane( message,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
pane.createDialog(null, "Nachricht manipulieren").setVisible(true);
int value = ((Integer)pane.getValue()).intValue();
if(value == JOptionPane.OK_OPTION) {
String s = n.getInhaltString();
String[] ss = s.split(",|=");
String ks = keys.get(cb.getSelectedIndex()).toString(ss[1]);
Nachricht nn = n.copy();
nn.setInhalt(ks);
cc.nachrichten.add(cc.nachrichten.indexOf(n)+1,nn);
cc.updateNachrichtenListe();
} // end of if
} // end of if
if (e.getSource() == emi && !n.getSended()) {
n.setStopped(true);
JTextArea mess = new JTextArea(n.getInhaltString());
JScrollPane scrollPane = new JScrollPane(mess);
mess.setLineWrap(true);
mess.setWrapStyleWord(true);
scrollPane.setPreferredSize( new Dimension( 500, 200 ) );
Object[] message = {"Nachricht", scrollPane};
JOptionPane pane = new JOptionPane( message,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
pane.createDialog(null, "Nachricht manipulieren").setVisible(true);
int value = ((Integer)pane.getValue()).intValue();
if(value == JOptionPane.OK_OPTION) {
n.setInhalt(mess.getText());
} // end of if
cc.updateNachrichtenListe();
}
if (e.getSource() == dmi1) {
n.generateHash();
cc.updateNachrichtenListe();
}
if (e.getSource() == dmi2) {
Nachricht dummy = new Nachricht("dummy","dummy",n.getInhaltString());
dummy.generateHash();
String ha2 = new String(dummy.getHashCode());
String ha = new String(n.getHashCode());
System.out.println(ha2+","+ha);
if(ha.equals(ha2)) {
JOptionPane.showMessageDialog(this,
"Der Hashcode der Nachricht stimmt mit dem übermittelten Hashcode überein",
"Bestätigung",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this,
"Der Hashcode der Nachricht passt nicht zum übermittelten Hashcode.",
"Fehler",
JOptionPane.ERROR_MESSAGE);
}
}
}
}

View file

@ -0,0 +1,98 @@
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Die Klasse MyServer verwaltet einen ServerSocket. Sie erstellt einen ServerSocket an einem
* bestimmten Port und wartet dort auf Clients. Es können mehrere Clients gleichzeitig angemeldet sein.
* Eine Klasse, die diesen Server benutzt, muss MyServerSocketListener implementieren. Sie wird dann
* über die Methode neuerClient informiert, wenn sich ein neuer Client am Server angemeldet hat.
* Beschreibung
*
*
* @version 1.0 vom 15.11.2012
* @author Thomas Schaller
*/
public class MyServer extends Thread {
// Anfang Attribute
private ServerSocket ss;
private int port;
private boolean aktiv = true;
private MyServerSocketListener listener;
// Ende Attribute
/** Dieser Konstruktor erzeugt einen neuen ServerSocket, startet ihn aber nicht sofort.
* @param listener Klasse, die MyServerSocketListener implementiert und dann über neue Clients und eingehende Nachrichten informiert wird.
* @param port Port, den der ServerSocket abhört.
*/
public MyServer(MyServerSocketListener listener, int port) {
this.port = port;
this.listener = listener;
try {
ss = new ServerSocket(port);
} catch(Exception e) {
System.out.println(e);
} // end of try
}
// Anfang Methoden
/** Liefert den Port, den der Server abhört.
* @return Port
*/
public int getPort() {
return port;
}
/** Startet das Abhören des Ports und das Annehmen der Clients
*/
public void starten() {
start();
}
/** Verwaltet das Annehmen der Clients (Diese Methode bitte nicht direkt aufrufen, sondern mit starten() aktivieren).
*/
public void run() {
aktiv = true;
try {
while(aktiv) {
System.out.println("Warte auf Client");
Socket s = ss.accept();
System.out.println("Client empfangen");
MySocket ms = new MySocket(s, listener);
listener.neuerClient(ms);
}
} catch(Exception e) {
System.out.println(e);
} // end of try
}
/** Bricht das Abhören des Ports ab. Es kann nicht wieder durch starten aktiviert werden. Dazu muss ein neuer Server erstellt werden.
*/
public void stoppen() {
aktiv = false;
try{
ss.close();
interrupt();
} catch( Exception e) {
System.out.println(e);
}
}
/** Meldet, ob der Server aktiv ist.
* @return true, falls der Server den Port abhört, sonst false.
*/
public boolean getAktiv() {
return aktiv;
}
// Ende Methoden
} // end of Server

View file

@ -0,0 +1,196 @@
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.nio.charset.StandardCharsets;
/**
* Die Klasse MySocket verwaltet eine Client-Server-Verbindung. Sie wartet auf eingehende Nachrichten und
* informiert ihren Listener, wenn eine Nachricht eingangen ist. Die Nachricht kann dann beim Socket abgeholt werden.
* Außerdem können Nachrichten in Form von Strings versendet werden.
* Der Listener wird außerdem informiert, wenn die Verbindung zusammengebrochen / beendet ist.
* Der Listener muss das Interface MySocketListener implementieren.
*
*
* @version 1.0 vom 15.11.2012
* @author Thomas Schaller
*/
public class MySocket extends Thread{
// Anfang Attribute2
private boolean aktiv;
private Socket socket;
private BufferedReader eingang=null;
PrintWriter ausgang=null;
MySocketListener listener=null;
// Ende Attribute2
/** Dieser Konstruktor erstellt einen MySocket aus einem schon vorhandenen Socket und ist für die Verwendung durch MyServer gedacht.
* @param s Socket, der durch MySocket verwaltet werden soll.
* @param listener Listener, der über eingehende Nachrichten und das Beenden der Verbindung informiert wird. Der Listener muss MySocketListener implementieren.
*/
public MySocket(Socket s, MySocketListener listener){
this.socket = s;
this.listener = listener;
try {
eingang = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ausgang = new PrintWriter(socket.getOutputStream());
aktiv = true;
this.start();
} catch(Exception e) {;
System.out.println(e);
e.printStackTrace();
aktiv = false;
} // end of try
}
/** Dieser Konstruktor erstellt einen neuen Socket. Er verbindet sich mit einem Server an der angegebenen Adresse unter dem angegebenen Port. Der Listener wird
* über eingehende Nachrichten und das Beenden der Verbindung informiert.
* @param address IP-Adresse oder Domain-Name des Servers
* @param port Portnummer, die der Server abhört
* @param listener Listener, der über eingehende Nachrichten und das Beenden der Verbindung informiert wird. Der Listener muss MySocketListener implementieren.
*/
public MySocket(String address, int port, MySocketListener listener) {
this.listener = listener;
try {
this.socket = new Socket(address, port);
eingang = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ausgang = new PrintWriter(socket.getOutputStream());
aktiv = true;
this.start();
} catch(Exception e) {
System.out.println(e);
e.printStackTrace();
aktiv = false;
} // end of try
}
// Anfang Methoden2
/** Verwaltet das Annehmen der Nachrichten (Diese Methode bitte nicht direkt aufrufen, sie wird automatisch gestartet).
*/
public void run(){
try {
while (aktiv){
if (listener != null && eingang.ready()) listener.nachrichtEmpfangen(this);
Thread.sleep(5);
}
}
catch (Exception e) {
if(socket!=null)try{socket.close();}catch(Exception ex){;}
System.err.println(e);
e.printStackTrace();
}
aktiv = false;
if (listener != null) listener.verbindungBeendet(this);
}
/** Liefert die eingangene Nachricht. Diese Methode bitte nur aufrufen, wenn der Listener über den Eingang einer Nachricht informiert wurde, da die Methode sonst bis
* zur nächsten eingehenden Nachricht wartet.
* @return Nachricht
*/
public String holeNachricht() {
try{
if (aktiv && eingang.ready()) {
String s = eingang.readLine();
System.out.println(s);
byte[] b = Base64.decode(s);
/* for (int i = 0; i < b.length ; i++) {
System.out.print(b[i]);
System.out.print(" ");
} // end of for
System.out.println("");*/
return s;
} // end of if
}
catch(Exception e) {
e.printStackTrace();
return null;
}
return null;
}
/** Versendet eine Nachricht an den Server.
* @param nachricht Zu sendender Text.
*/
public void sendeNachricht(String nachricht) {
try {
//byte[] b = nachricht;
/* for (int i = 0; i < b.length ; i++) {
System.out.print(b[i]);
System.out.print(" ");
} // end of for
System.out.println("");*/
//ausgang.println(Base64.encode(nachricht));
ausgang.println(nachricht);
// System.out.println(Base64.encode(nachricht));
ausgang.flush();
} catch(Exception e) {
System.out.println(e);
e.printStackTrace();
if (listener != null) listener.verbindungBeendet(this);
aktiv = false;
}
}
/** Bricht eine bestehende Client-Server-Verbindung ab.
*/
public void trenneVerbindung() {
aktiv = false;
if (socket != null) {
try {
socket.close();
} catch(Exception e) {
System.out.println(e);
e.printStackTrace();
}
} // end of if
socket = null; // end of try
}
/** Liefert den Socket der Verbindung. Kann benutzt werden, um dann aus dem Socket weitere Informationen wie IP-Adressen oder Portnummern zu ermitteln.
* @return Socket, der Verbindung.
*/
public Socket getSocket() {
return socket;
}
/** Liefert den Status der Verbindung.
* @return true, falls die Verbindung noch aktiv ist, sonst false.
*/
public boolean isAktiv() {
return aktiv;
}
/** Räumt alles auf, damit der Thread nicht weiterläuft (bitte nicht aufrufen).
*/
public void finalize() {
// Schließen der Streams und des Sockets, wenn
// die Verbindung gelöscht wird wird
try {
trenneVerbindung();
}
catch(Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
// Ende Methoden2
}

View file

@ -0,0 +1,19 @@
import java.net.ServerSocket;
import java.net.Socket;
/**
* Listenerdefinitionen für MyServer und MySocket.
* Klassen, die mit diesen beiden Klassen arbeiten müssen diese Listener implementieren.
*
* @version 1.0 vom 15.11.2012
* @author Thomas Schaller
*/
interface MySocketListener { // Der Listener wird über folgendes informiert...
void nachrichtEmpfangen(MySocket s); // am Socket ist eine Nachricht eingegangen. Diese kann dann mit s.holeNachricht() abgeholt werden.
void verbindungBeendet(MySocket s); // die Verbindung wurde beendet oder ist zusammengebrochen.
}
interface MyServerSocketListener extends MySocketListener {
void neuerClient(MySocket s); // ein neuer Client hat sich mit dem Server verbunden.
}

View file

@ -0,0 +1,183 @@
/**
*
* description
*
* @version 1.1 from 30.01.2020
* Änderungen: Hash-Funktion verbessert, damit ähnliche Texte nicht so ähnliche Hashes bekommen
* @author
*/
import java.util.ArrayList;
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
public class Nachricht {
// Anfang Attribute
private byte[] inhalt;
private String absender;
private String empfaenger;
private ArrayList<Key> keys;
private ArrayList<Key> hashKeys;
private byte[] hashCode;
private long time;
private boolean stopped;
private boolean sended;
// Ende Attribute
public Nachricht(String absender, String empfaenger, String inhalt) {
setInhalt(inhalt);
this.absender = absender;
this.empfaenger = empfaenger;
this.keys = new ArrayList<Key>();
this.hashKeys = new ArrayList<Key>();
this.hashCode = ("").getBytes() ;
this.time = System.currentTimeMillis();
this.stopped = false;
this.sended = false;
}
public Nachricht(String absender, String empfaenger, byte[] inhalt, byte[] hashCode) {
this.inhalt = inhalt;
this.absender = absender;
this.empfaenger = empfaenger;
this.keys = new ArrayList<Key>();
this.hashKeys = new ArrayList<Key>();
this.hashCode = hashCode;
this.time = System.currentTimeMillis();
this.stopped = false;
this.sended = false;
}
public Nachricht(String absender, String empfaenger, String inhalt, ArrayList<Key> keys, ArrayList<Key> hashKeys) {
setInhalt(inhalt);
this.absender = absender;
this.empfaenger = empfaenger;
this.keys = (ArrayList<Key>)keys.clone();
this.hashKeys = (ArrayList<Key>) hashKeys.clone();
this.hashCode = ("").getBytes() ;
this.time = System.currentTimeMillis();
this.stopped = false;
this.sended = false;
}
public Nachricht(String absender, String empfaenger, byte[] inhalt, byte[] hashCode, ArrayList<Key> keys, ArrayList<Key> hashKeys) {
this.inhalt = inhalt;
this.absender = absender;
this.empfaenger = empfaenger;
this.keys = (ArrayList<Key>)keys.clone();
this.hashKeys = (ArrayList<Key>) hashKeys.clone();
this.hashCode = hashCode;
this.time = System.currentTimeMillis();
this.stopped = false;
this.sended = false;
}
// Anfang Methoden
public String getInhaltString() {
return new String(inhalt);
}
public byte[] getInhalt() {
return inhalt;
}
public void setInhalt(String inhalt) {
this.inhalt = inhalt.getBytes();
}
public void setInhalt(byte[] inhalt) {
this.inhalt = inhalt;
}
public String getAbsender() {
return absender;
}
public void setAbsender(String absender) {
this.absender = absender;
}
public String getEmpfaenger() {
return empfaenger;
}
public void setEmpfaenger(String empfaenger) {
this.empfaenger = empfaenger;
}
public Nachricht copy() {
Nachricht n = new Nachricht(absender, "", inhalt, hashCode, keys, hashKeys);
return n;
}
public void addKey(Key k) {
keys.add(k);
}
public ArrayList<Key> getKeys() {
return keys;
}
public void addHashKey(Key k) {
hashKeys.add(k);
}
public ArrayList<Key> getHashKeys() {
return hashKeys;
}
public void generateHash() {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
hashCode = Base64.encode(digest.digest(getInhaltString().getBytes(StandardCharsets.UTF_8))).substring(0,10).getBytes();
} catch(Exception e) {
System.out.println(e);
hashCode = new byte[0];
}
}
public byte[] getHashCode() {
return hashCode;
}
public void setHashCode(byte[] hashCode) {
this.hashCode = hashCode;
}
public int getRestzeit() {
if (sended || stopped) {
return 0;
} // end of if
return 10 - (int) ((System.currentTimeMillis()-this.time)/1000);
}
public boolean getSended() {
return sended;
}
public void setSended(boolean s) {
sended = s;
}
public boolean getStopped() {
return stopped;
}
public void setStopped(boolean s) {
stopped = s;
}
// Ende Methoden
}

View file

@ -0,0 +1,53 @@
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.*;
import java.awt.FontMetrics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
//pic erbt von Panel - spart eine Klasse
public class PicPanel extends JPanel {
ArrayList<Key> keys;
public PicPanel(ArrayList<Key> keys){
this.keys = keys;
}
public void drawCenteredString(String s, int xx, int yy, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = xx- fm.stringWidth(s) / 2;
g.drawString(s, x, yy);
}
//paintComponent überschreiben, Image zeichnen, super-Aufruf nicht vergessen
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int x = 0; x < keys.size(); x++) {
g.drawImage(keys.get(x).getImage(),x*32,2,this);
drawCenteredString(keys.get(x).getName(),x*32+16,50,g);
}
}
public String getToolTipText(MouseEvent evt) {
int k = evt.getX() /32;
if (keys.size()>k) {
return "<html><p width=400><b>Exponent:</b><br>"+keys.get(k).getE()+"</p><p width=400><b>Modul:</b><br>"+keys.get(k).getN()+"</p></html>";
} // end of if
return "Schlüsselspeicher";
}
}

View file

@ -0,0 +1,130 @@
/**
*
* Beschreibung
*
* @version 1.0 vom 14.01.2016
* @author
*/
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class RSA {
// Anfang Attribute
private int SIZE = 1024;
private int BLOCKSIZE = 2;
private BigInteger n;
private BigInteger p, q;
private BigInteger PhiN;
private BigInteger e, d;
// Ende Attribute
public RSA() {
generateKey();
}
public RSA(int bits) {
SIZE = bits;
generateKey();
}
// Anfang Methoden
public BigInteger getN() {
return n;
}
public void setN(BigInteger n) {
this.n = n;
}
public void generateKey() {
/* Step 1: Select two large prime numbers. Say p and q. */
p = BigInteger.probablePrime(SIZE, new Random());
q = BigInteger.probablePrime(SIZE, new Random());
/* Step 2: Calculate n = p.q */
n = p.multiply(q);
/* Step 3: Calculate ø(n) = (p - 1).(q - 1) */
PhiN = p.subtract(BigInteger.valueOf(1));
PhiN = PhiN.multiply(q.subtract(BigInteger.valueOf(1)));
/* Step 4: Find e such that gcd(e, ø(n)) = 1 ; 1 < e < ø(n) */
/* do {
e = new BigInteger(2 * SIZE, new Random());
} while ((e.compareTo(PhiN) != 1)
|| (e.gcd(PhiN).compareTo(BigInteger.valueOf(1)) != 0));
*/
/* Als e wird in der Praxis immer 65537 verwendet*/
e = BigInteger.valueOf(65537);
/* Step 5: Calculate d such that e.d = 1 (mod ø(n)) */
d = e.modInverse(PhiN);
}
public Key getPublicKey() {
return new Key("Ö",e,n);
}
public Key getPrivateKey() {
return new Key("P",d,n);
}
public static Key getPublicKeyZert() {
return new Key("ZS",new BigInteger("92020722032510237098687730821345002475852926519687505393637258322619905644760889379395080699744916048107242925967027699181978133434386836838764269376892530783630654811456718501622805"+
"0429691604569763800205767093030273564571085665400962405818664165449303338714877264756844232275146244572923302600861123085509774896697571445612708416287450226532029033236047907922857453176065518750862719489230457831441"+
"7173388889137991463283210462111428501392067084189267999492753829846440287839192599579471258088572439889541316908031255266831632514679577179417418047234941358616454031601382865835722476368628684965351829298264441751183"+
"4765538945638034868762252381408904028140439409187378031978842476147164936819798249655054427494851690069200746638913551812853454469432164195272770583598350122258729847670066946154048177957396760843403465486329401836814"+
"9990639814827911842782103318445952572226732629881400041393595241900643703238957157012120488385905509895908742240747739986701990654721595793098375922165943034668657422624955521278896354123265004069921640297875759614496"+
"742155179442639630932330086817709676636648111414906681085732877503585719166804978513181384327884382400889164642851924835156763044152821991745397448110186145769503874106711784628283015"),
new BigInteger("5139848029926993084030177297754816256127765376419362760006875069769259661872914759939556724394537974685918407976961929857609117001554132888941990323118389734140650301936109978057312726558318809808688530"+
"99773725611495268508136211646337118765334983074807622287602613120954964306249607670374637031866390157648764929632399710705078606495073542059188462314599000331802944594967393118351191103705051281495305712977081775868511"+
"76669514447588704897250963384817831024230705289577095855693680350648450932456258694411608347436126446258894555954026134724123826545582729849892381402885181473492517034956094364025058973837607228431208754049905489662832"+
"09739142470309153125447402018234554037154608185773467018511970065694249410104669788842146660693780223399943991335490758657838309774214025815008528258836495746672516751271291457802304100684624522436687990982028305751185"+
"48926383285704725365240957188638904019694020065564925826265319075541291979464737277137720345398870073684194532135223107690328725385189503977019793221936587592861157513836453534572733867521266351697630143131367971098119"+
"501251155238775343770355444640289263220749122642671050995480950737812740946324944965924224677968141284858329942830891138365556546396148300565405098100850501841"));
}
public static Key getPrivateKeyZert() {
return new Key("ZSP", new BigInteger("88405792460374902093708496634850741322105940917351683868541504012830882621245768251091372013156643395250448929783142177860165402492647945415104962343917444383622605496273629917298"+
"610236655119004745619089104384026215301496147234635587743965575319499761064848213230757151103779005504514500023252356175847116728347255176088139236137082826628487749466300296767988898076628975938940677076738206736367"+
"124996756783169958055053177519677571981271713255438344078311774536073940876121321362816462939120383991608570431036543882874480977769541084535126636925352742738338245898199820269860018114420772543302483230833480292931"+
"352334730109447074945409204173176619699849050721926499420093861285836519963502042472293474805213779251720392591031533706581969617690636531135793143059665641797414237435624262623024366515969141242459029652395794721850"+
"8436689537023284104630131792447652257617740873015159381631615655581919939509498869888015294276578911842474036086993469464623230276020243502751167826145879239288526145360234428912097606211745547385659522887117076882491"+
"04675147998869220229602216434114268798658103586693108736443392251539998599980668517520134276984180168498165513964507909008004400364235467465743076136818915438381335591270604629182883277111"),
new BigInteger("5139848029926993084030177297754816256127765376419362760006875069769259661872914759939556724394537974685918407976961929857609117001554132888941990323118389734140650301936109978057312726558318809808688530"+
"99773725611495268508136211646337118765334983074807622287602613120954964306249607670374637031866390157648764929632399710705078606495073542059188462314599000331802944594967393118351191103705051281495305712977081775868511"+
"76669514447588704897250963384817831024230705289577095855693680350648450932456258694411608347436126446258894555954026134724123826545582729849892381402885181473492517034956094364025058973837607228431208754049905489662832"+
"09739142470309153125447402018234554037154608185773467018511970065694249410104669788842146660693780223399943991335490758657838309774214025815008528258836495746672516751271291457802304100684624522436687990982028305751185"+
"48926383285704725365240957188638904019694020065564925826265319075541291979464737277137720345398870073684194532135223107690328725385189503977019793221936587592861157513836453534572733867521266351697630143131367971098119"+
"501251155238775343770355444640289263220749122642671050995480950737812740946324944965924224677968141284858329942830891138365556546396148300565405098100850501841"));
}
// Ende Methoden
public static void main(String[] args) {
RSA r = new RSA(2048);
Key o = r.getPublicKey();
Key p = r.getPrivateKey();
/*BigInteger i = new BigInteger("2237891328923");
System.out.println(i.toString());
byte[] b = o.convert(i);
BigInteger j = o.convert(b);
System.out.println(j.toString());
System.out.println(new String(o.encrypt(("Hallo").getBytes())));
System.out.println("------------");
System.out.println(new String(p.encrypt(o.encrypt(("Hallo").getBytes()))));
*/
System.out.println(o.getE());
System.out.println("---");
System.out.println(p.getE());
System.out.println("---");
System.out.println(o.getN());
}
} // end of RSA

View file

@ -0,0 +1,25 @@
/**
*
* description
*
* @version 1.0 from 20.01.2016
* @author
*/
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class TestRSA {
public static void main(String[] args) {
RSA rsa = new RSA();
Key k1 = rsa.getPublicKey();
Key k2 = rsa.getPrivateKey();
System.out.println("Keys generiert");
BigInteger i = BigInteger.valueOf(100);
BigInteger j = k1.encrypt(i);
BigInteger z = k2.encrypt(j);
System.out.println(i.toString()+"\n"+j.toString()+"\n"+z.toString());
System.out.println(k1.encrypt(k2.encrypt("Hallo Leute, dies ist ein langer Text")).trim());
}
}

View file

@ -0,0 +1,186 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
/**
* @author JavaDigest
*
*/
public class TestRSA2 {
/**
* String to hold name of the encryption algorithm.
*/
public static final String ALGORITHM = "RSA";
/**
* String to hold the name of the private key file.
*/
public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";
/**
* String to hold name of the public key file.
*/
public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
/**
* Generate key which contains a pair of private and public key using 1024
* bytes. Store the set of keys in Prvate.key and Public.key files.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws FileNotFoundException
*/
public static void generateKey() {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(PRIVATE_KEY_FILE);
File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
// Saving the Public key in a file
ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();
// Saving the Private key in a file
ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The method checks if the pair of public and private key has been generated.
*
* @return flag indicating if the pair of keys were generated.
*/
public static boolean areKeysPresent() {
File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);
if (privateKey.exists() && publicKey.exists()) {
return true;
}
return false;
}
/**
* Encrypt the plain text using public key.
*
* @param text
* : original plain text
* @param key
* :The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
/**
* Decrypt text using private key.
*
* @param text
* :encrypted text
* @param key
* :The private key
* @return plain text
* @throws java.lang.Exception
*/
public static String decrypt(byte[] text, PrivateKey key) {
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
/**
* Test the EncryptionUtil
*/
public static void main(String[] args) {
try {
// Check if the pair of keys are present else generate those.
if (!areKeysPresent()) {
// Method generates a pair of keys using the RSA algorithm and stores it
// in their respective files
generateKey();
}
final String originalText = "Text to be encrypted. Dies ist ein längerer Text.";
ObjectInputStream inputStream = null;
// Encrypt the string using the public key
inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
final PublicKey publicKey = (PublicKey) inputStream.readObject();
final byte[] cipherText = encrypt(originalText, publicKey);
// Decrypt the cipher text using the private key.
inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
final String plainText = decrypt(cipherText, privateKey);
// Printing the Original, Encrypted and Decrypted Text
System.out.println("Private Key"+privateKey);
System.out.println("Original: " + originalText);
System.out.println("Encrypted: " +cipherText.toString());
System.out.println("Decrypted: " + plainText);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 984 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 999 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1,002 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 994 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 969 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 992 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 981 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 977 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 975 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,12 @@
= Material der ZPG IMP 10:
|===
|Zuordnung| Informationsgesellschaft und Datenschutz
|Klassenstufe| IMP 10
|Bildungsplanbezug |
|Werkzeug| Chatprogramm mit asymmetrischer Verschlüsselung
|Autoren| Thomas Schaller
|===
== Inhalt
Chatprogramm zur Veranschaulichung von asymmetrischer Kryptologie. Nachrichten können verschlüsselt und signiert werden. Ein Man in the Middle Angriff kann simuliert werden.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 B