Code Snippets für VS Lab Test Beinhaltet TCP, UDP, RMI sowie diverse Security Dinger. Großteils wurde der Code von Lab1 Lab2 genommen, bzw. aus dem TUWEL Faq. Es kann natürlich sein, dass Fehler enthalten sind, also bitte mit kritischem Auge betrachten ;). Exceptions wurden hier für die Leserlichkeit komplett weggelassen, Eclipse wird einen jedoch darauf aufmerksam machen, vondem her sollte das kein großes Problem sein. Viel Spaß beim Lernen. TCP: Client Setup for short communication: UDP: Client Setup for short communication RMI: Client Setup Server Setup SECURITY: BASE64 en/decoding Secure Random Number AES encryption / decryption RSA encryption / decryption HMac
TCP: synchronous Server Client communication. Client Setup for short communication: Socketsocket=newSocket("localhost", 1337); BufferedReaderreader=newBufferedReader(new InputStreamReader(socket.getInputStream())); // thetrueisveryimportantfortheautoflush PrintWriterwriter=newPrintWriter(socket.getOutputStream(), true); // writetoserver writer.println("requesttoserver"); // printoutanswer System.out.println(reader.readLine()); // Don tclosewriterorreaderbecausetheythrowexceptions. this.socket.close(); // ServerSocketonlyneedsport, nohost ServerSocketserverSocket=newServerSocket(1337); SocketclientSocket=serverSocket.accept(); BufferedReaderreader=newBufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriterwriter=newPrintWriter(clientSocket.getOutputStream(), true); Stringrequest=reader.readLine(); /* * DOSOMETHINGWITHREQUEST:D */ // answertoclient writer.println("responsetoclient"); // Don tclosewriterorreaderbecausetheythrowexceptions. if(serversocket!=null&&!serversocket.isclosed()) serversocket.close(); if(clientsocket!=null&&!clientsocket.isclosed()) clientsocket.close();
UDP: a synchronous Server Client communication. Client Setup for short communication // CLIENTHASEMPTYCONSTRUCTOR DatagramSocketsocket=newDatagramSocket(); StringmessageForUDP="THISISAMESSAGE"; byte[] buffer=messageforudp.getbytes(); // createthepacket DatagramPacketpacket=newDatagramPacket(buffer, buffer.length, InetAddress.getByName(serverhost), udpport); // sendthepacketoff socket.send(packet); // Nowwegonnawaitforapacket, setupthebufferandpacketfirst: buffer=newbyte[1024]; packet=newdatagrampacket(buffer, buffer.length); // thereceiveblocksandwaitstillpacketarrives socket.receive(packet); // Printoutwhatwereceived System.out.println(newString(packet.getData())); socket.close(); // SERVERHASPORTINCONSTRUCTOR DatagramSocketsocket=newDatagramSocket(udpPort); // Nowwegonnawaitforapacket, setupthebufferandpacketfirst: byte[] buffer=newbyte[1024]; DatagramPacketpacket=newDatagramPacket(buffer, buffer.length); // thereceiveblocksandwaitstillpacketarrives socket.receive(packet); Stringrequest=newString(packet.getData())); Stringresponse=newString("response"); // ToreturntoClientwegetAddressandPortfromPacket InetAddressaddress=packet.getAddress(); intport=packet.getport(); buffer=response.getbytes(); packet=newdatagrampacket(buffer, buffer.length, address, port); socket.send(packet); socket.close();
RMI: registry thingy for putting addresses and looking them up. Client Setup // getremoteserverobjectfromregistry Registryregistry=LocateRegistry.getRegistry(host, port); IServerRemoteremote=(IServerRemote) registry.lookup(servername); // nowyoucanusethemethodsfromiserverremote(examplefrommuster test) remote.bye(); Server Setup // createregistryonport Registryregistry=LocateRegistry.createRegistry(port); // remoteobistheremoteobject, inourcaseaninstanceofiserverremote( > this) IServerRemoteremote=(IServerRemote) UnicastRemoteObject.exportObject(remoteOb, 0); // bindremoteobjecttoanameintheregistry registry.bind(bindingname, remote); // THAT SITATTHISPOINT, NOWFORCLOSING // remoteobissameasbefore( >this) andtrueisforforcingit UnicastRemoteObject.unexportObject(remoteOb, true); if(registry!=null){ // don tforgettounbindafterunexporting registry.unbind(bindingname); UnicastRemoteObject.unexportObject(registry, true); } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // theiserverremotehasttousetheremoteinterfaceandallmethodsthatwillbe // calledoverrmihavetothrowtheremoteexception
SECURITY: BASE64 en/decoding // getarandomstringmessageinbyte byte[] message=newstring("thisisamessage").getbytes(); // encodethemessage byte[] base64encoded=base64.encode(message); // decodethemessage byte[] base64decoded=base64.decode(base64encoded); // togofrombytetostring StringmessageEncoded=newString(base64encoded); Secure Random Number SecureRandomsecureRandom=newSecureRandom(); finalbyte[] number=newbyte[32]; securerandom.nextbytes(number); AES encryption / decryption // CREATEIV >nothingbutarandom16bitbytearray SecureRandomiv=newSecureRandom(); finalbyte[] number=newbyte[16]; iv.nextbytes(number); // CREATEtheKEY, AESthereforeAESInstance KeyGeneratorgenerator=KeyGenerator.getInstance("AES"); // KEYSIZEisinbits generator.init(keysize); SecretKeykey=generator.generateKey(); // ENCRYPTYOURINPUT Ciphercipher=Cipher.getInstance(AESCONFIG); cipher.init(cipher.encrypt_mode, key, newivparameterspec(iv)); byte[] encrypted=cipher.dofinal(input); // ENCRYPTIONANDDECRYPTIONISTHESAMEEXCEPTFORTHECIPHER_MODE!!!!!!! // DECRYPTYOURINPUT Ciphercipher=Cipher.getInstance(AESCONFIG); cipher.init(cipher.decrypt_mode, key, newivparameterspec(iv)); byte[] decrypted=cipher.dofinal(input);
RSA encryption / decryption // RSAWEUSETHEPUBLICANDPRIVATEKEYS, shouldbegivenasfile, alsowedon t // needanivobject // ENCRYPTYOURINPUTWITHPUBLICKEY Ciphercipher=Cipher.getInstance(RSACONFIG); cipher.init(cipher.encrypt_mode, publickey);//!!!! PUBLICKEY byte[] encrypted=cipher.dofinal(input); // ENCRYPTIONANDDECRYPTIONISTHESAMEEXCEPTFORTHECIPHER_MODEANDKEY!!!!!!!! // DECRYPTYOURINPUTWITHPRIVATEKEY Ciphercipher=Cipher.getInstance(RSACONFIG); cipher.init(cipher.decrypt_mode, privatekey);//!!!! PRIVATEKEY byte[] decrypted=cipher.dofinal(input); HMac // HMACCHECK // keyisthesecretkey, messageisthemessagewereceived // ThisisbasicallyalsohowyoucreateahMac MachMac=Mac.getInstance("HmacSHA256"); hmac.init(key); hmac.update(message.getbytes(standardcharsets.utf_8)); byte[] calculatedhash=hmac.dofinal(); // receivedhashisthehashthatwereceivedwiththemessage returnmessagedigest.isequal(calculatedhash, receivedhash);