network communication encryption in java

2020-02-01 04:16发布

问题:

A friend and me are working on a Java Game with a client/server - architecture. It is working well, but i ran into a problem. We use TCP Sockets for networking between server and client. Our network protocol isnt encrypted and can just be read by anone who bothers to watch the stream.

We thought about how we could apply some kind of cryptography to it to hide login information and prevent people to write their own clients. But basic things like adding/substracting bytes seems pretty easy to figure out.

What are the usual methods used to encrypt network communication for games( or at least game login information )? And having written the server and client in java, are there any useful java libraries?

回答1:

Use public-key encryption (RSA for example) and implement something like the SSL Handshake, or of course use SSL - here you can see an example.

Here's a simplified sequence:

  • the server sends his public RSA key to the client
  • the client generates a symmetric key (using AES for example)
  • the client encrypts the symmetric key with the server's public key and sends it to the server
  • the server decrypts the received symmetric key

Now both the client and the server have a key which no one eavesdropping can know. Then use that key to encrypt all data.



回答2:

SSL(Secure Sockets Layer) is popular to handle this kind of problem.



回答3:

Look at the javax.crypto library or bouncyCastle.

Both provide cryptographic primitives, also for encryption. Depending on how secure you want to have it, you can use symmetric or assymetric crypto. However, also think about key management in advance. Where do you store your private/shared key.

If it is a client-server, the best way would be to use assymetric crypto (i.e. RSA, Elliptic Curve) and give every user a certificate signed with the key of the server (note, this is TLS (formerly called SSL)). This way you can check if the user logging on is authentic. However, you dont prevent custom clients since the user has to have everyone can just copy the certificate.

In practice, it is quite hard to prevent custom clients.



回答4:

You can use Ciphers. Some more examples here and here