• 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
https://www.neowin.net/forum/topic/1120844-help-with-des-and-aes/
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.

  • 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 >.<

  • 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.

  • 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....

  • 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...

  • 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).

  • 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?

  • 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

  • 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.

  • 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

  • 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]

  • 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...

  • 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

  • 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 :)

  • 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 ...

  • 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 )

This topic is now closed to further replies.
  • Posts

    • Ooooh! Two editorial from Paul Hill on the same day! Is it my birthday or something? 😉 Okay, let's see if I get it right. SearXNG develops a meta-search engine app. Individuals install it on their relays. Users connect to these relays to have their own identity-stripping meta-search engine instead of relying on DuckDuckGo. And some of these volunteers have listed their SearXNG instances on SearX.space. That was a lot of wrap my head around. I hope I haven't missed anything.
    • You sound like some Ukrainians in Crimea before 2014: "I didn't vote for USSR disbanding - I want Ukraine to be part of Russia again" 🤣
    • Uninstalr 3.1 by Razvan Serea Introducing Uninstalr: Easy to use and very accurate software uninstaller for Windows. It can uninstall multiple apps at the same time and we think it’s pretty cool. Developed with expertise by Macecraft Software - the minds behind jv16 PowerTools. Key Features Batch uninstall many apps at the same time. Supports unattended uninstallation of apps. Supports monitoring of new software installations. Also detects portable apps and previously uninstalled software leftovers. Shows all the data added to your system by installed software on a file by file basis. Shows all the data it will remove before starting the uninstallation. Filter and search the list of installed software. According to our benchmark, Uninstalr is the most accurate software uninstaller by leaving the least amount of leftovers when uninstalling apps. Supports detection and uninstallation of Microsoft Store, Steam, Big Fish Game System, Chocolatey, NuGet and Ninite installed software. Supports Windows Dark Mode. Supports Windows 11, 10, 8 and 7. Comes with these translations builtin: Chinese Simplified, Chinese Traditional, Czech, Danish, English, Filipino, Finnish, French, German, Greek, Hindi, Hungarian, Indonesian, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Romanian, Slovak, Spanish, Swedish, Thai, Turkish, Ukrainian and Vietnamese. Has a single executable file portable version and a normal setup version. Uninstalr is freeware, lightweight and easy to use. No bells and whistles, no nonsense. Uninstalr’s custom uninstallation engine has a dedicated support for the detection and uninstallation of 15 types of apps: Normal Windows apps Microsoft Store apps Portable apps Chocolatey apps Ninite apps PortableApps.com apps Steam games EA App games Epic Games Store games Riot platform games GOG Galaxy games WarGaming.net games Battle.net games itch.io games Big Fish platform games Uninstalr 3.1 changelog: Key Changes Uninstalr now starts and shows the list of installed apps faster after the initial scan has been completed, and with much smaller memory usage. Uninstalr now detects and highlights apps that automatically start with Windows. Greatly improved the detection of portable apps. Improvements New feature: Uninstalr now detects and highlights apps that automatically start with Windows. New feature: Uninstalr now highlights possible leftovers and apps from Russia and China. This can be disabled from the Settings. New feature: A new filter that allows you to show only software that is installed to other than the system drive. New feature: Users can now select to always do the deepest and the most accurate scan for installed apps, at the cost of the analysis taking a longer time. Greatly improved the detection of portable apps, such as added dedicated support for MiTeC, EZ Tools and SysInternals tools. Improved support for portable apps installed via Windows System Control Center (WSCC). NirSoft portable apps are now listed with "NirSoft" prefix for easier identification. Improved the speed of uninstalling apps. The main installed software listing search will now find "Xbox GameBar" if you search for "Game bar" and vice versa. The tooltip now displays more detailed information of the installed apps, such as its registry key and uninstaller path. The links in the About section now look more like clickable links. The main menu is now more clearly indicated in the main user interface. Microsoft Teams Meeting Add-in for Microsoft Office ships with some Windows 11 installations and is now considered a builtin Windows app and only listed if builtin Windows apps filter is enabled. Added a Help button to the main user interface that opens the help section of the website. Added an option not to close Uninstalr after uninstallation. If you open the Uninstalr website from the app, the website now receives the version number of your current Uninstalr version and warns you if you are using anything but the latest version. Improved the accuracy of the New Software Monitor. Improved confirmation messages for Steam and other platform related uninstalls. Improved the uninstallation performance of Steam games. Fixes: Known bug fixed: Some installed app names are capitalized incorrectly, such as "CCleaner Portable" is listed as "ccleaner portable". Known bug fixed: Some apps can be listed twice, for example, Smart Defrag can be listed once as Smart Defrag and then Smart Defrag Home. Known bug fixed: On the pre-uninstallation screen, the Scripts checkbox can be checked by default on Dark Mode but not on the normal mode. Known bug fixed: Perform Deep Analysis can be started only by clicking the button, not via the Right Click menu, main menu or F4 keyboard shortcut. Muse Hub could be incorrectly listed as Adobe Muse. SyncTrayzor was incorrectly detected as two unrelated software, SyncTrayzor and Syncthing. Smart Defrag was incorrectly listed twice as Smart Defrag 11 and Smart Defrag Home. It was possible to enter non-printable characters to the search input boxes of the main screen, and the path listing screen, which caused the UI to look funny. Changing the translation from Settings, especially many times in a row, caused the UI to distort. If you had multiple instances of portable apps on your system, such as the 64b and 32b versions of the same portable app, typically only one of them was detected, not both. In some very rare cases, Uninstalr UI could start with random characters in its search input boxes, which could make the UI look rather confusing. This was a rare issue, only reported by two users. The pre-uninstallation screen could display non-existing paths for example as the software's installation directory or main exe file. This was a cosmetic issue. New Software Monitor cannot detect the installation of Claude. Selecting all the found software made the UI look funny with the top panel covering everything else (because the names of all the selected software were listed there). Sometimes a Steam game could be listed a normal app instead of a Steam game. If the system restart after an uninstallation is delayed, e.g. because of Windows Updates being installed, this additional delay is incorrectly added to the time how long the uninstallation process took. This cosmetic bug could cause the program incorrectly report an uninstallation time longer than the actual uninstallation time. Uninstalling Minecraft could simply fail. The Only scan the system drive for installed apps setting does not fully work. If some apps are installed to a non system drive and this setting is enabled, the app could still be detected and listed on the main user interface. Changing any settings could also incorrectly alter the Only Scan The System Drive For Installed Apps setting. Microsoft OneDrive and Copilot are not always detected. If you enter something to the search filter field, then select the text and press the Delete key, this triggers the Uninstall button click even if your intent was to delete the text input. If you press the F5 key to refresh the screen during the uninstallation loading screen, the program will crash. If you enabled some setting, such as "Do not analyze installed app installation sizes", it could automatically be unchecked later. Uninstalr doesn't warn you if you try to remove Fortec antivirus. There should be a warning if user attempts to remove any antivirus or antimalware type program. Such programs should not be uninstalled using a third party uninstaller, as they are typically protected against automated uninstallation, for security reasons. With "Do not analyze installed app installation sizes" option checked from the Settings, Uninstalr could still display some installation size related elements in the UI which was confusing. The "Only scan the system drive" option moved under Improve Scan Speed from the General settings. If two software have the exact same name and version number, selecting both of them for uninstallation fails because only one is actually selected. Sorting the installed apps by size sometimes fails and the order is incorrect. The "Don't show which paths are currently analyzed" did not work correctly - some parts of the UI still show the currently analyzed path with this setting checked. The "Don't list software less than 10 MB" filter did not work correctly - some apps smaller than 10 MB could still be listed. Uninstalr could start very quickly and display an empty list of detected apps. Restarting the app usually fixed the issue and the list of installed apps was properly displayed. If you placed portable Uninstalr to a same folder with other portable apps, those were not detected because Uninstalr automatically added its installation folder to the ignore list. When trying to uninstall some specific software, Uninstalr could get stuck on the Searching for more data relating to the app phase. Uninstalr could sometimes do a silent uninstallation even if user had unchecked the Perform a silent uninstallation option. Known issues: Uninstalr can fail to run with an Out Of Memory error in systems that have a lot of installed apps. Using the New Software Monitor tool multiple times during one session can cause the program to get stuck on the Scanning stage. The "uninstallation completed" message box sometimes closes when the user moves the mouse cursor over the button before user clicks it. There is no feedback for the user after Fix Information feature has been used. The Right Click menu's Select by publisher option can display the number of apps per each publisher without correct vertical alignment. The default user interface might not display all of the found installed apps if you have over 600 installed apps. If you do, using the Screen Reader Compatible Interface solves the issue. Leftover apptype filter checkbox is shown in red font only in Dark Mode. Clicking the app's icon from the Windows Taskbar doesn't minimize/restore the app like other apps. The warning about an app that user wishes to uninstall being related to some other app user did not select can sometimes be inaccurate. If app's language is changed without restarting Uninstalr, the list of installed software might not automatically refresh. When software is being uninstalled, the UI can say it is processing paths unrelating to the uninstalled app. This is purely cosmetic and does not mean these paths are removed. Uninstalr might not properly detect and/or uninstall Steam games if they are installed to a drive different than Steam's default location in C:\. You might see "This action is only valid for products that are currently installed" error message from Windows Installer during uninstallation. This is a cosmetic issue. Download: Uninstalr 3.1 | 7.1 MB (Free, paid version available) Download: Uninstalr Setup 3.1 View: Uninstalr Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I and many others did not vote to get out of the E.u because of Putin or Farage, we did so for our own reasons. You don't have to tel me what my own did or did not do when it comes to the E.U. The EEC is or was the European Economic Community, a different beast to what the E.U is now.The EEC was a mainly about trading, the E.U have gone far beyond that and as I have said before, is now more of a United States of Europe. The U.K did not vote to join a United States of Europe. Anyway, they did not want us in there in the first place, Charles de Gaulle stopped us joining as he claimed we didn’t agree with the core ideas of integration. He was not wrong and that is why we voted out of the E.U when the time came. I was not old enough to vote the first time. My only regret is that we did not have the referendum years ago and got out years ago. If we rejoined, we would have to agree to join the Euro and no doubt Schengen, agree with freedom of movement, we have enough problem with people coming over here as it is. i have no problem with people coming over here if they work and don't try to push their way of life onto us. The E.U has a currency, freedom of movement, an anthem a flag, a parliament, well they are there, not sure if they do anything. Don't sound like something that is just for trading. Oh yeah, also wanted a euro Army. How many stupid rules have the E.U made that we had to follow? I doubt I will see the Uk rejoin the E.U, which suits me. Oh yeah, my partner is Polish, she came over here before Poland joined the E.U and she got fed up of people just coming over here with ease, while she had to struggle. She is now a British citizen and have been for a fair few years
    • Hello, Paul. Thanks for the editorial. It was interesting. I'm going research more into the app and its concept. Of course, if you know me at all, you know that I'd say your articles needs some editing! I always do, don't I? For instance, the article occasionally mentions relays before defining it.
  • Recent Achievements

    • Week One Done
      flexorcist earned a badge
      Week One Done
    • One Month Later
      Woland13 earned a badge
      One Month Later
    • Week One Done
      Woland13 earned a badge
      Week One Done
    • One Year In
      bernmeister earned a badge
      One Year In
    • Week One Done
      Scoobystu earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      495
    2. 2
      +Edouard
      226
    3. 3
      PsYcHoKiLLa
      153
    4. 4
      Steven P.
      75
    5. 5
      FloatingFatMan
      71
  • Tell a friend

    Love Neowin? Tell a friend!