Hi, hope you have a good Christmas :) Mine was not bad, but here I am to write a little more.
Besides eating chocolates, these days I have continued some of my school works. One in specific is a game for android, that soon I will talk more in detail.
Besides eating chocolates, these days I have continued some of my school works. One in specific is a game for android, that soon I will talk more in detail.
One important thing in games is the possibility of save the scores in a way that no one can forge, at least directly. So how do this in Java?
The simplest idea that I remembered was to put the scores in a particular class, make it serializable, apply a xor and write it to a file, to recover do the reverse process.
So this is our class
class Person implements Serializable{ String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
In this example, our key will be 10
byte key=10;
To convert from object to array and from array to object, we will use these two functions
public static byte[] object2Bytes(Object object) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(object); } catch (IOException ioe) {} return baos.toByteArray(); } public static Object bytes2Object(byte[] bytes){ Object object = null; try{ object = new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); }catch(Exception e){} return object; }
And finally the main code
public static void main(String[] args) { Person person = new Person("asd", 10); byte []dataArray; byte key=10; try { FileOutputStream fos = new FileOutputStream("file.dat"); dataArray=object2Bytes(person); for (int i = 0; i < dataArray.length; i++) { dataArray[i]=(byte) (dataArray[i]^key); } fos.write(dataArray); fos.close(); } catch (Exception e) { e.printStackTrace(); } dataArray=new byte[512]; try { FileInputStream fis = new FileInputStream("file.dat"); fis.read(dataArray); fis.close(); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < dataArray.length; i++) { dataArray[i]=(byte) (dataArray[i]^key); } Person person2 = (Person) bytes2Object(dataArray); System.out.println(person2.getName()+" "+person2.getAge()); }
The output that you get is "asd 10"
But now let's take a look in the file "file.dat", first without encryption
Note the "asd" name and "0a" age (10 in hexadecimal) near the end
and now with encryption
As you can see, something so simple and that is done in 5 minutes, can get away the more newbies. Obviously, something as simple is far from secure, the ideal is to use a larger key and use some algorithm really safe.
Which you like this idea :)
No comments:
Post a Comment