• 0

help with DES and AES


Question

hi I have posted something like this before but I am still tackling the problem....

I am trying to encrypt bytes and then add a second encryption then remove the first without removing the second.... I have my reasons for this I need help with this not an alternative....

the encryption can be alternative so DES + DES or AES + DES or AES + AES or anything thing else but it has to be like this ... here is my code so far .... I have got the encryption layers on ... its just getting them off im struggling with (one page test code)....im getting (given final block is not correctly padded)


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class ObjectCrypter {

public static void main(String[] argv) {

try {

String str = "moo";

byte[] byted = str.getBytes();

Cipher desCipher;
Cipher enCipher;

KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();

desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEd = desCipher.doFinal(byted);

System.out.println("DES?" + new String(textEd));



byte[] byt = textEd;

KeyGenerator keygenerat = KeyGenerator.getInstance("AES");
SecretKey myD = keygenerat.generateKey();

enCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

enCipher.init(Cipher.ENCRYPT_MODE, myD);
byte[] tex = enCipher.doFinal(byt);

System.out.println("AES?" + new String(tex));

desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(tex);

System.out.println("it work?" + new String(textDecrypted));





}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}catch(NoSuchPaddingException e){
e.printStackTrace();
}catch(InvalidKeyException e){
e.printStackTrace();
}catch(IllegalBlockSizeException e){
e.printStackTrace();
}catch(BadPaddingException e){
e.printStackTrace();
}
}

}
[/CODE]

if you can help it would be great :)

Link to comment
Share on other sites

Recommended Posts

  • 0

:woot: best post in this entire forum since a long while.

thanks :)

well I will answer the first two sub titles :p the 3rd one will require more reading but I have to get my washing out before i go to class xD ......

firstly thank you for taking the time to show interest it shows you are taking me seriously...

secondly This is my aim and how I am trying to get there...

this P2P connection will have a host so far im starting off easy, the host will be decided by the people using the chat (e.g. run host.class)

the host will be listening on the desired port (default probs 4444 or 5555 something like that) the client then connects to host ... yes target will need to be specified by client (I am trying to do this with as little database work as possible but I am not closed to it )

this program is not designed for use by a large populous its a program that will be off the radar for now and used for specific private communications....

I was thinking about using private and public key methods but im not sure how they work yet....

There will be another chat I will be making in the future which will use usernames and such both with encryption and without (one is a project I have to do other is just because I want to ) ....

like I said rest will have to wait!!! also no saved chats ever ! all will be burnt ...

Okay, small user base, we have a server, but no database so you've got no password protected user account mechanism, which imposes limits on what you can do. Let's see what we can come up with...

Users simply specify in their client the alias they wish to use. The client connects to the server, giving it the alias, which takes note of it and the IP address and port number of the computer registering it, and holds this information in memory with all of the others. When a chat client is started, it retrieves from the server a list of every user connected to the server, and periodically checks for updates. This list is presented to the user, from which they select someone to try and establish a chat session with.

Each user's client generates a key pair, and can save it (as opposed to generating a fresh one for each session). Public keys can be exchanged directly when establishing a chat session with someone. With the key saved and re-used the next time you use the chat client, this makes friend-list functionality viable. With friend list functionality, a copy of the friend's public key is saved. The next time you connect to them, from any IP address, or with any alias, the copy of your public key that they saved allows you to be recognised. To actually be highlighted as being online in another user's friend list, when you connect to the service, your certificate or at least the short identifier for it, should be uploaded to the server; This would then be distributed to other clients when they update their copy of the list of people connected to the server.

The key exchange between users needs to be verified though through other means. If verification is not done, there's no guarantee of any security what-so-ever. If users verifying each other's keys will be a pain, and it very likely will, you could use the 'web-service as a middle-man' approach that I described in my last post - create a key pair for the web service, and give a copy of the public key to everyone using that server, making sure they know they have got the correct one, and it hasn't been intercepted and switched (perhaps a big problem). Users would provide the web service's public key to their clients, which would use it to encrypt and send the user's public key to the server, which would de-crypt it, re-encrypt with the others user's public key, and pass it on to them. But as described in my last post, the admin of the web server could snoop! Users directly exchanging keys and verifying them is the correct and most secure way to do it, but a pita.

If a user needs to replace their key for any reason, the existing entry in someone else's friend list will be redundant. You would have to make contact with them, explain that you've changed your key, prove to them that it really is you, and do a verification of the new key. Unless you contact someone to get them to replace their friend list entry for you, there's no way that they would know that their existing one is redundant, they'll just think that you never come online any more.

I think that covers everything...

Oh, something I meant to talk about in my earlier post but forgot about - SPI, NAT & UPNP

If another chat client, or the web service, tries to send a communication of any kind to your client, that isn't a direct reply to a communication sent out by your client, then it's going to get blocked. To get around this, just like utorrent, your client is going to have to punch a hole through to the outside world with UPNP in order to allow all of the incoming traffic to pass through to your chat client.

Link to comment
Share on other sites

  • 0

kinda want to get rid of my posts because i feel so stupid now ... can not believe I did such a stupid mistake im so angry with my self

It's particularly amusing given you flamed off at someone and told them not to underestimate you :p

Also, I doubt this will end up having any relevance to your current work given how you've proceeded, but it's worth a read: http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange

It's a very cool idea and should help you with basic crypto things in the future.

Another "for extra reading" recommendation is "The Code Book" by Simon Singh. Very good place to start if you want a crash course in Cryptography :)

Good luck with your project >.<

Link to comment
Share on other sites

  • 0

Also, I doubt this will end up having any relevance to your current work given how you've proceeded, but it's worth a read: http://en.wikipedia....an_key_exchange

Very interesting!! A couple of possible issues using it here though:

  • A piece of information needs to be shared between the two users. If a malicious person were to observe this piece of information being exchanged, that's not a problem, however if they were able to perform a man in the middle attack, then this would be useless. To eliminate the possibility of a man in the middle attack, you'd have to exchange it some other way, or at least confirm it some other way, i.e. over the phone.
  • Additionally, if knowing that the person on the other end really is who they say they are, you still need the additional external verification.

Link to comment
Share on other sites

  • 0

It's particularly amusing given you flamed off at someone and told them not to underestimate you :p

Also, I doubt this will end up having any relevance to your current work given how you've proceeded, but it's worth a read: http://en.wikipedia....an_key_exchange

It's a very cool idea and should help you with basic crypto things in the future.

Another "for extra reading" recommendation is "The Code Book" by Simon Singh. Very good place to start if you want a crash course in Cryptography :)

Good luck with your project >.<

in all fairness I did just copy and paste it without much effort xD but even still i should of noticed .... but I have made great steps today in my code i am currently exchanging public keys over the web .... which is a lil annoying actually .... I may post back cause im stuck ... the person B has got the public key ... but i am having issues getting it to be a BigInteger .... it does not seem to like parsing a string to a big int....

Link to comment
Share on other sites

  • 0

saying that actually .... here is the bit of code im having issues with ......


while ((inputLine = in.readLine ()) != null)
{
if (sy == 1) {
Sm = inputLine;
System.out.println(Sm);


String[] parts = Sm.split("!e! ", 2);
String string1 = parts[0];
String string2 = parts[1];

String j = string1.replace("!m!", "");
m = new BigInteger(j);
e = new BigInteger(string2);
}
[/CODE]

one String is received and it is split up, ann manipulated to form raw keys .... as you can see ... this now makes me feel a little bit better after my stupid mistake as if you could see all my work its rather fancy :3 long winded probably ....but fancy .... so yes any suggestions as to why it does not like turning them into bigints.... they are all numbers no letters or symbols...

Link to comment
Share on other sites

  • 0
  • DH key exchange is still hard. It's no easier to crack the exchange process than to attempt to crack the the key used to encode a message directly. I've got a video that explains the process in easy-to-follow terms that I use to teach my non-math major friends. I'll find the link and edit it in.
  • You can use DH key exchange to establish a secure channel. Once you've established the channel you can verify the party your connecting to using any of the standard methods.

The video was indeed helpful, thanks for that.

I'm not certain if it came across clearly, but it wasn't the key exchange itself I was questioning though, I can see with the video how that's secure, it's the fact that an attacker sat between bob and alice could intercept the exchange, so they never talk directly to each other, but instead without knowing are talking through the attacker.

The solution you proposed has the advantage of making it easy to to exchange public keys but ultimately doesn't address the problem of verification. Alice still needs a way to ensure that any given public key belongs to Bob. If you introduce a third party you just ask bob or alice to trust that third party instead of trusting eachother. Our goal isn't (and can't be) to ensure that a particular person belongs to a particular key. We can only hope to ensure that the person we talk to today is the same as the person we talked to yesterday.

We can do that by taking advantage of the way private and public keys are related. Alice generates a hash of a message she wants to send to bob. Alice encrypts the hash with her private key. Alice sends the message and the encrypted hash to bob. Bob recieves the message generates a hash of it. Bob decrypts Alice's encrypted hash using Alice's public key which he has. Bob compares the hash he's generated with the one alice sent him.

If they match then bob knows he's talking to whoever claimed to be alice yesterday.

If they don't match then he knows that eve is interfering in some way.

Bob has no way of knowing that the public key he has belongs to alice and there is no system of verification that can be done without involving trust somewhere in the chain. If we want to trust that we're talking to alice then we should let her pick the locations where we can find her public key. If we dictate one central location then it's possible eve can compromise that site. Alice would notice her public key doesn't match but would have no way to communicate that (in a way we could trust) to anybody (because eve controls the one trusted location for public keys). If alice can publish her key 50 places then it's much more difficult for eve. Eve would need to compromise all of those locations simultaneously. Breaking only one location means bob could spot eve's medling by comparing the key from 1 site to the others that alice has claimed to publish it. All keys should be the same.

EDIT

I agree with everything you've said, I believe we are on the same wavelength.

With the bit underlined, knowing that you're talking to the same person as last time is meaningless if both conversations are going through an attacker, you're just confirming that you're going through the very same attacker and nothing has changed. Ensuring that you're talking directly to the other person and not through an attacker is the key problem, which is what you're talking about more of in the last quoted bit above. (Just wanted to make this a little clearer for others, not you, I can tell that you get this).

Link to comment
Share on other sites

  • 0

The video was indeed helpful, thanks for that.

I'm not certain if it came across clearly, but it wasn't the key exchange itself I was questioning though, I can see with the video how that's secure, it's the fact that an attacker sat between bob and alice could intercept the exchange, so they never talk directly to each other, but instead without knowing are talking through the attacker.

I agree with everything you've said, I believe we are on the same wavelength.

With the bit underlined, knowing that you're talking to the same person as last time is meaningless if both conversations are going through an attacker, you're just confirming that you're going through the very same attacker and nothing has changed. Ensuring that you're talking directly to the other person and not through an attacker is the key problem, which is what you're talking about more of in the last quoted bit above. (Just wanted to make this a little clearer for others, not you, I can tell that you get this).

if the key problem is the middle man ... why encrypt at all ? isnt the point of encryption to screw over the middle man in the first place?

Link to comment
Share on other sites

  • 0

Alice and Bob want to write letters to each other without Eve finding out. Alice and Bob live in an apartment that eve manages.Consider the different ways communication that could happen:

i get your point now ... hmm interesting to consider .... static ips would help here ....maybe but obviously .....you would want to be able to initiate without any issues.... maybe a log in function ? like skype or msn ... would help but would allow less anomity ...but then you could just run through the TOR network

Link to comment
Share on other sites

  • 0

if the key problem is the middle man ... why encrypt at all ? isnt the point of encryption to screw over the middle man in the first place?

Of course it is, I'm not sure that I follow...

With both public-private key cryptography and DH, an exchange needs to take place of a piece of information crucial to establishing a secure channel of communication. In public-private key cryptography, this is the exchange of each other's public keys, in DH, this is a few numbers. In both cases, if this is observed only, it doesn't matter, the channel will be secure, however if an attacker is sitting between the two of them and intercepts this exchange then we do not have a secure channel, although it may look like it from the perspective of the two users. It's secure between Alice and the attacker, and between Bob and the attacker, but the attacker is silently decrypting, re-encrypting, and re-transmitting every message.

What you need is a way of ensuring that this data has really reached its destination, and not been intercepted and switched with the attacker's own. This is the tricky part. The proper way to do this is for the two users to communicate in another way, to verify that what they have received is correct (or to have agreed on a shared secret at some point in the past), which could be done for example by talking over the phone (if you'll recognise their voice and you're sure an attacker will not have the capability to intercept that and pretend to be them), or by meeting in person.

This is obviously a hassle, but with public private key cryptography can be minimised. For example, Alice and Bob meet in person to exchange keys, and they sign each others keys. John is friends with Alice and meets in person to exchange and sign keys. John then befriends Bob and wishes to communicate securely with him. Since Alice has already signed Bob's key, and John already trusts Alice's key, John does not have to actually meet with Bob. All that's needed to trust a new key is that at least one signature on it is from a key that you already trust. (Note that the work of exchanging keys and signing do not have to actually be done during the meetup, the keys could be exchanged beforehand, and just the key's shorter "fingerprint" compared. The signing of each others keys could be done later and uploaded to a public key server, so John here can get a copy of Bob's public key with Alice's signature already attached).

I suggested that this verification might be a problem for your system, it depends on people knowing each other in real life, or rather knowing at least one of the other users in real life, and establishing a network of trust through signing of each other's public keys. I outlined another option that you could take, which is to allow the web server to act as a "legitimate" middle man. Every user has a copy of the server's public key, and so can securely transport a copy of their own public key to it, and the server can then securely transfer it to the other user. It would not be possible for an attacker to compromise either key exchange. This simplifies things for the users who no longer need to meet up and verify something, however the server itself is a big weak point. The admin of the web server has the power to intercept communications, the government may force the admin to do so on their behalf, or an attacker could potentially break into the server and compromise everything. Whether you choose do this is your decision to make, I just wanted to cover it as part of my analysis. For users who do know each other in real life and are willing to do a proper exchange, this option would be much worse for them, but for users who do not know each other, even through a chain of other users, and therefore cannot validate each other's keys, as long as they are establishing connection to the right user on the system, public keys can be exchanged securely (with the exception of the server itself, which they would have to accept a compromise on).

Evn suggested that our goal should not be to try and know that a particular person owns a particular public key, but simply that once you've got a public key, that all future communications are coming from that same key, which is easy. This is indeed easy, however as I said in my reply, if the original communication was intercepted by an attacker, then by verifying that it's the same key, all you're doing is verifying that the same attacker(s) is still watching and no other attackers have joined in.

Evn also talked about the difficulties in obtaining the correct public key without a proper "meet up" type verification, which needs to involve some level of trust. Trusting a single service to store your public key would be foolish, because the service could just swap it out with one they've generated themselves. Evn suggested that storing it in multiple places, comparing copies from multiple places, and allowing the owner of the key to dictate where you go to get them from is much better, and I agree. However, this is by no means perfect. Firstly a powerful entity, e.g. the government, could easily have the capability to compromise this, by intercepting every transfer of a key on to and down from the internet. Additionally, without meeting in person, or talking over the phone, if instead Alice tells Bob through some digital communication which location(s) to visit to get the key, there's no guarantee that communication itself isn't compromised, or perhaps the user types in the correct url (or clicks the correct link), but it's invisibly redirected to a certificate owned by an attacker such as the government. There is absolutely no possible way to be sure that the exchange hasn't been compromised without meeting the other user in person, and checking with them.

Evn has now taken this even further to talk about the issue of knowing whether a person you don't already know really is know they say they are if you meet in real life to do the key exchange. This is certainly an interesting topic, and obviously only applies to people you don't already know. Someone you do already know might of course be lying to you about their identify also, but knowing that would be besides the point, you simply want to talk to that individual securely, no matter their real secret identity. With someone you don't know, let's say one of us wishes to talk securely to another, and need to do a secure key exchange, if we met in person, how would we know if the person we meet is the right person? In such a case all you can really do at the end of the day is make a judgement call, based on the real life likely hood of their being imposter, etc.

What we need to do here is take a look at the people who might be using the system and how they know each other.

  • If all users of the system already know each other, i.e. you're just building this for use by your group of friends, then the best solution will be to establish a chain of trust by signing each other's keys until everyone has at least one signature from someone else in the group.
  • If you're involving users who do not know each other in real life but do know each other through some other means, verification could be done through those other means. For example with us, we could verify each other's keys through Neowin. We would have to each assess the likely hood of our exchanges being compromised (e.g. by Neowin, by our ISP, by our government), and just accept that it's not a 100% guarantee, but probably not likely.
  • If you're dealing with people who have never met each other, one of them has simply discovered the other through a chat service and initiated a chat session, then there's absolutely no way to guarantee security. However the method of having the web server as a "legitimate" middle man has advantages in some ways here.

Another interesting aspect to think about in all of this that's not been mentioned yet, is what if an attacker compromised the client application itself. I.e. you publish the software on a website, a user goes to download it, but an attacker has hacked the server and replaced it, or intercepts the download and serves a hacked copy instead. You'd need to take that into consideration also. To solve this, you'd need to sign the application, and provide your developer key to users. As a user, ensuring that the developer key that you have is correct has the same problems as already discussed.

Link to comment
Share on other sites

  • 0

you will be happy to know i got my chat program working (mostly ...) i just have to finish a few things then i have a public and private key set up :D will post it once im done, just incase anyone wants to see/improve ... if i get time will be done within a day .... if not a couple of days (its very limited in what it does but the security is there ) .... my program shares keys on connection, fresh everytime... no reusing of keys

Link to comment
Share on other sites

  • 0

Of course it is, I'm not sure that I follow...

With both public-private key cryptography and DH, an exchange needs to take place of a piece of information crucial to establishing a secure channel of communication. In public-private key cryptography, this is the exchange of each other's public keys, in DH, this is a few numbers. In both cases, if this is observed only, it doesn't matter, the channel will be secure, however if an attacker is sitting between the two of them and intercepts this exchange then we do not have a secure channel, although it may look like it from the perspective of the two users. It's secure between Alice and the attacker, and between Bob and the attacker, but the attacker is silently decrypting, re-encrypting, and re-transmitting every message.

What you need is a way of ensuring that this data has really reached its destination, and not been intercepted and switched with the attacker's own. This is the tricky part. The proper way to do this is for the two users to communicate in another way, to verify that what they have received is correct (or to have agreed on a shared secret at some point in the past), which could be done for example by talking over the phone (if you'll recognise their voice and you're sure an attacker will not have the capability to intercept that and pretend to be them), or by meeting in person.

This is obviously a hassle, but with public private key cryptography can be minimised. For example, Alice and Bob meet in person to exchange keys, and they sign each others keys. John is friends with Alice and meets in person to exchange and sign keys. John then befriends Bob and wishes to communicate securely with him. Since Alice has already signed Bob's key, and John already trusts Alice's key, John does not have to actually meet with Bob. All that's needed to trust a new key is that at least one signature on it is from a key that you already trust. (Note that the work of exchanging keys and signing do not have to actually be done during the meetup, the keys could be exchanged beforehand, and just the key's shorter "fingerprint" compared. The signing of each others keys could be done later and uploaded to a public key server, so John here can get a copy of Bob's public key with Alice's signature already attached).

I suggested that this verification might be a problem for your system, it depends on people knowing each other in real life, or rather knowing at least one of the other users in real life, and establishing a network of trust through signing of each other's public keys. I outlined another option that you could take, which is to allow the web server to act as a "legitimate" middle man. Every user has a copy of the server's public key, and so can securely transport a copy of their own public key to it, and the server can then securely transfer it to the other user. It would not be possible for an attacker to compromise either key exchange. This simplifies things for the users who no longer need to meet up and verify something, however the server itself is a big weak point. The admin of the web server has the power to intercept communications, the government may force the admin to do so on their behalf, or an attacker could potentially break into the server and compromise everything. Whether you choose do this is your decision to make, I just wanted to cover it as part of my analysis. For users who do know each other in real life and are willing to do a proper exchange, this option would be much worse for them, but for users who do not know each other, even through a chain of other users, and therefore cannot validate each other's keys, as long as they are establishing connection to the right user on the system, public keys can be exchanged securely (with the exception of the server itself, which they would have to accept a compromise on).

Evn suggested that our goal should not be to try and know that a particular person owns a particular public key, but simply that once you've got a public key, that all future communications are coming from that same key, which is easy. This is indeed easy, however as I said in my reply, if the original communication was intercepted by an attacker, then by verifying that it's the same key, all you're doing is verifying that the same attacker(s) is still watching and no other attackers have joined in.

Evn also talked about the difficulties in obtaining the correct public key without a proper "meet up" type verification, which needs to involve some level of trust. Trusting a single service to store your public key would be foolish, because the service could just swap it out with one they've generated themselves. Evn suggested that storing it in multiple places, comparing copies from multiple places, and allowing the owner of the key to dictate where you go to get them from is much better, and I agree. However, this is by no means perfect. Firstly a powerful entity, e.g. the government, could easily have the capability to compromise this, by intercepting every transfer of a key on to and down from the internet. Additionally, without meeting in person, or talking over the phone, if instead Alice tells Bob through some digital communication which location(s) to visit to get the key, there's no guarantee that communication itself isn't compromised, or perhaps the user types in the correct url (or clicks the correct link), but it's invisibly redirected to a certificate owned by an attacker such as the government. There is absolutely no possible way to be sure that the exchange hasn't been compromised without meeting the other user in person, and checking with them.

Evn has now taken this even further to talk about the issue of knowing whether a person you don't already know really is know they say they are if you meet in real life to do the key exchange. This is certainly an interesting topic, and obviously only applies to people you don't already know. Someone you do already know might of course be lying to you about their identify also, but knowing that would be besides the point, you simply want to talk to that individual securely, no matter their real secret identity. With someone you don't know, let's say one of us wishes to talk securely to another, and need to do a secure key exchange, if we met in person, how would we know if the person we meet is the right person? In such a case all you can really do at the end of the day is make a judgement call, based on the real life likely hood of their being imposter, etc.

What we need to do here is take a look at the people who might be using the system and how they know each other.

  • If all users of the system already know each other, i.e. you're just building this for use by your group of friends, then the best solution will be to establish a chain of trust by signing each other's keys until everyone has at least one signature from someone else in the group.
  • If you're involving users who do not know each other in real life but do know each other through some other means, verification could be done through those other means. For example with us, we could verify each other's keys through Neowin. We would have to each assess the likely hood of our exchanges being compromised (e.g. by Neowin, by our ISP, by our government), and just accept that it's not a 100% guarantee, but probably not likely.
  • If you're dealing with people who have never met each other, one of them has simply discovered the other through a chat service and initiated a chat session, then there's absolutely no way to guarantee security. However the method of having the web server as a "legitimate" middle man has advantages in some ways here.

Another interesting aspect to think about in all of this that's not been mentioned yet, is what if an attacker compromised the client application itself. I.e. you publish the software on a website, a user goes to download it, but an attacker has hacked the server and replaced it, or intercepts the download and serves a hacked copy instead. You'd need to take that into consideration also. To solve this, you'd need to sign the application, and provide your developer key to users. As a user, ensuring that the developer key that you have is correct has the same problems as already discussed.

the simple way for a select group of friends is to simply ask them questions only they would know ... on the encrypted level once you confirm its them ... you know their key .... at the moment this is a private chat project .... it will become a massive anyone can use it system in the future .... but at the moment im keeping it as is (if i work to fast I might screwed over, as Il be using the advanced thing in a research paper I have to start next year)

the host lol ... I am not quite done I still have to finish decryption .... but i have made a mistake in the clientside .....and i have no idea what i have done...


import java.net.*;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.awt.event.*;
import java.math.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
public class SwingChatServer extends SwingChatGUI
{
/**
*
*/
private static final long serialVersionUID = 1L;
PrintWriter out;
BufferedReader in;
BufferedReader stdin;
public ButtonHandler bH;
static int sy = 0;
private BigInteger e;
private BigInteger m;
private String Se;
private String Sm;
private Key jim;
PublicKey pubKey;
String inputLine, outputLine;
public ButtonHandler bHandler = new ButtonHandler();

public SwingChatServer (String title)
{
super (title);
bHandler = new ButtonHandler ();
sendButton.addActionListener (bHandler);

bH = new ButtonHandler();
synco.addActionListener( bH );
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()==sendButton) {


if (sy == 1) {
//EtS = txArea.getText ();
try {
kpairs();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} else {


}
}
if (event.getSource()==synco){

String syn = "Accepted press 'sync' again";
String outputLine = syn;
out.println (outputLine);
sy = 1;


}
}
}

public void run () throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
{
ServerSocket serverSocket = null;

try
{
serverSocket = new ServerSocket (1978);
}
catch (IOException e)
{
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept ();
}
catch (IOException e)
{
System.err.println ("Accept failed.");
System.exit(1);
}
out = new PrintWriter (clientSocket.getOutputStream (), true);
in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
//stdin = new BufferedReader (new InputStreamReader (System.in));
out.println ("Welcome to the Chat Server\n");
while ((inputLine = in.readLine ()) != null)
{
if (sy == 1) {
Sm = inputLine;
System.out.println(Sm);


String[] parts = Sm.split("!e! ", 2);
String string1 = parts[0];
String string2 = parts[1];


String j = string1.replace("!m! ", "");

System.out.println("_______---------------______________----------->" + j);
m = new BigInteger(j);
e = new BigInteger(string2);

//e = new BigInteger(Se);
if (Sm != null) {




sy = 2;
kpairs();
}
}
System.out.println ("Server < " + inputLine);
rxArea.setText (inputLine);
}

out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
public void kpairs() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{

if (sy == 0) {

try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
jim = privateKey;
out.println("public key: " + publicKey);
}
catch (NoSuchAlgorithmException e) {

}

}

if (sy == 1) {

RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
pubKey = fact.generatePublic(keySpec);

outputLine = txArea.getText ();
System.out.println ("Client > " + outputLine);

byte[] src = outputLine.getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(src);
out.println(new String(cipherData));


}

}
public static void decrypt() {

}

public static void main(String[] args)//throws IOException
{
SwingChatServer f = new SwingChatServer ("Chat Server Program");

f.pack ();
f.setVisible(true);
try
{
try {
f.run ();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to: 194.81.104.118.");
System.exit(1);
}
}
}
[/CODE]

Link to comment
Share on other sites

  • 0

i get your point now ... hmm interesting to consider .... static ips would help here ....maybe but obviously .....you would want to be able to initiate without any issues.... maybe a log in function ? like skype or msn ... would help but would allow less anomity ...but then you could just run through the TOR network

Absolutely none of what you've described is going to provide any sort of guarantee of establishing a secure exchange. Not if you want something that will be absolutely secure against absolutely any adversary, including your own government.

  • Static IP. Many users such as myself have dynamic IP's, so this doesn't help us. Many people sit behind a NAT, and therefore could impersonate each other, etc
  • Login. This only allows users to secure a particular alias and lock others out from using it. It in no way proves that the account belongs to the person it appears to belong to. Additionally a public key stored in the account could have been replaced by the admin of the service, etc.
  • TOR. The idea with TOR is that your traffic disappears into a network through which it can't be traced back to you. It in itself is not a perfect solution and I personally do not trust it. While traffic is likely securely transmitted within TOR, the end nodes, where traffic enters and exits TOR can be monitored. The traffic coming out of the end node is not encrypted as it travels to the final destination. Who owns the nodes, the government could own many of them?! How is data transferred into TOR from the client securely? (seems to be a mixture of DH and TLS, well DH is something we've already discussed and cannot be secure on it's own. SSL/TLS is worthless in my opinion with the web's current HTTPS infrastructure, though it's use here might perhaps be okay and actually work securely if a self-signed certificate is being used and embedded in the TOR application, though you then need to trust the TOR developers and the copy of the application you've downloaded (as well as your operating system if we're really going to go that far). Ultimately though, TOR isn't going to actually help us one bit here.

you will be happy to know i got my chat program working (mostly ...) i just have to finish a few things then i have a public and private key set up :D will post it once im done, just incase anyone wants to see/improve ... if i get time will be done within a day .... if not a couple of days (its very limited in what it does but the security is there ) .... my program shares keys on connection, fresh everytime... no reusing of keys

Re-read everything that's been written, what you're building is in no way going to be secure.

the simple way for a select group of friends is to simply ask them questions only they would know ... on the encrypted level once you confirm its them ... you know their key

With a group of friends you already know, you'd meet them in person and verify each other's keys. If you're suggesting not doing this and instead establishing a connection to them, with what you hope to be a secure channel, and asking a question you hope that only they know the answer to in order to be sure you're connected to the right person... well I don;t know whether to go cry in despair, or come and smack you around the head with a heavy book :p I hope I misunderstood...

Link to comment
Share on other sites

  • 0

With a group of friends you already know, you'd meet them in person and verify each other's keys. If you're suggesting not doing this and instead establishing a connection to them, with what you hope to be a secure channel, and asking a question you hope that only they know the answer to in order to be sure you're connected to the right person... well I don;t know whether to go cry in despair, or come and smack you around the head with a heavy book :p I hope I misunderstood...

haha I know what you are saying! trust me I do ... im sure if you have read any of my posts im bad at explaining ...

I get the whole point of that key ... and noteting who you are connected to ... I personally think you are thinking to big scale for what im doing right now but I will have to do what you are suggesting .... which will probs involve mysql server (if I can ever get this damn driver working) ...

I could send a file to the other person containing the key and modulus but I dunno I guess im someone who is on the thinking line "no evidence, no crime" kind of thing while you are "know your friends and you will know your enemy" I dont think my ways are wrong (and im sure many would disagree) and I dont think yours are either .... I suppose its all opinion of what would be ideal ....

I dunno this requires some thought of what I want to achieve .... I know I want security, who I am talking to is not a concern for me ...because to understand the conversation you would have to be the person I want to talk to ....plus the person who is for now meant to be the other person to this program will be on the phone to me (skype) ... but as I said I also want to make this a big program ...when i change this to android I will probs make a file within the system...gah so much to consider at 5am

Link to comment
Share on other sites

  • 0

Having a history with security let me divulge my knowledge...

In the big large world of large and private companies and whatnot, you don't deal with 'we want 100% secure unhackable encryption and programs', you deal with % certainty that the information you've got is legitimate and % of it which is true, and % change it's been read by someone else.

Nothing is 100%, not even military can get 100%!

So don't worry if you can't get near 100% :p that'd be normal.

There's loads of factors that can influence them, if you're using signed PKI certificates, a hacker doesn't have to nick your certificates to be able to read or send false data, they can extract them server the server that signed them, for instance, they could forensically extract them from a USB/PC/Hard drive you've chucked.

As mad as it may seem, your system being not 100% secure is fine :)

Link to comment
Share on other sites

  • 0

It probably wouldn't take more than half an hour to get a proof of concept server running node or sinatra up on heroku...might make a fun project

I do not understand this line?

hi sorry it took so long to reply I have been working on loads of different piece of software I came back to this one today about an hour ago I have got it encrypting over the network ... once I got the decryption working (5mins if there are no bugs) then I will work on improving, my biggest down fall is adding features after the aim of the program is complete, so my code is about to get REALLY messy ...

Link to comment
Share on other sites

  • 0

I was just thinking out loud that it might be fun to bang out a chat server that shuttled encrypted messages between clients. Heroku is a cloud computing platform, Node and Ruby programming languages/environments that are really easy to get up and running on that platform.

Refactoring is easy if you've been keeping up on tests. Rather than accepting that things get hard once you get past half a dozen functions you should learn to use tests to help you develop sane code and testing to ensure you don't ruin everything. It's never a bad time to start writing tests for your code.

I always work on individual functions away from my main code if possible to see if they will work ..... though at the moment I am having trouble with the final method of my code ... the decrypting ... it does not seem to like the cipher.dofinal

byte[] cipherData = cipher.doFinal(src);

I cannot work out why .... i must have a typo or something somewhere I like your suggestion and I did think about something last night in regards to the chat system you fore mentioned I have many servers at my disposel for testing it will probs be the 4rd step I take in this project (2nd is getting it connect to a damn database for logins and 3rd is android )

Link to comment
Share on other sites

This topic is now closed to further replies.