Monday, December 20, 2010

SmartFoxServer public key return

Next up is the return of our server's public key for the user. Lets start by building our message from the server. Open NetBeans, in our [GameName]Extension project you want to open the [GameName]Account class. We are going to add a couple more properties that we will need later as well as 2 new functions. First is the function I forgot to add when i posted the constructor: readyCipher(). This function takes our private key and sets up the cypher to decrypt all incoming data. First we need a PrivateKey declared, so go up to where you see private PublicKey pubKey; and under it add

private PrivateKey privCipherKey;


Next we need to store off that key while we set up for decryption



    private void readyCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException {
        cipher = Cipher.getInstance("RSA");
        KeyFactory fact = KeyFactory.getInstance("RSA");
        privCipherKey = fact.generatePrivate(GetPrivateKey());
        cipher.init(Cipher.DECRYPT_MODE, privCipherKey);
    }

Now that our keys are ready and our cipher is is set to decrypt we need to be able to turn around and send our server's public key for this client back to the client so that the client can decrypt anything we send to them. If you conpare this to our last tutorial you will see that we package up the key the exact same way. We create the "mod" and "exp" keys as ByteArrays from our server's public key. We then wrap that up into another object calling it "key".
    public ISFSObject serverPublicKeyToSFSObject() {
        ISFSObject tr = new SFSObject();

        tr.putByteArray("mod", GetServerPubKey().getModulus().toByteArray());
        tr.putByteArray("exp", GetServerPubKey().getPublicExponent().toByteArray());

        ISFSObject data = new SFSObject();
        data.putSFSObject("key", tr);

        return data;

    }

And the last thing to do from the Java side is to send the public key. Do to this, we open up the World class and go down to our addPlayer function. Between players.add(player) and didAddPlayer = true; we want to add this line of code:
extension.send("publickey", player.serverPublicKeyToSFSObject(), user);
This will tell our extension to get our public key SFSObject and send it to our new player with the message type being "publickey".

Thats it for NetBeans. We have returned our data. Following these last few tutorials will give you the information necessary to send any kind of message. There will be a follow up tutorial on encrypting and decrypting the data, we just won't be covering that today.

Next time we will cover the last portion of our first message, Unity3D's handlers and storing our server public key.

No comments: