android本地数据加密

做游戏难免需要存储一些用户关于本游戏的数据,这些数据如果不是十分绝密,一般会被开发者用明文存放在一个本地数据文件中。大多数玩家是不会去故意查找这些数据并修改的,但是游戏好玩了话,喜欢破解数据并发到网上的还是大有人在的。为此,我们需要对本地额数据进行加密处理。

这篇文章主要介绍怎么对本地数据进行加密,可以做到本地数据文件不可修改,不可覆盖。

1.思路:主要思路是利用手机的uuid做密钥,来生成加密后的数据。获取本地数据的时候再根据uuid来解密。因为uudi的不同造成了即使加密算法即使被破解了,你修改了数据文件后在运行时读取数据的时候也会因为密钥的不同得不到正确的数据。

2.做法:

public String encrypt(String seed, String cleartext) {

if (!(“”.equals(seed)) && !(“”.equals(cleartext))) {

byte[] rawKey;

try {

rawKey = getRawKey(seed.getBytes());

byte[] result = encrypt(rawKey, cleartext.getBytes());

return toHex(result);

} catch (Exception e) {

e.printStackTrace();

}

}

return null;

}

 

public String decrypt(String seed, String encrypted) {

if (!(“”.equals(seed)) && !(“”.equals(encrypted))) {

byte[] rawKey;

try {

rawKey = getRawKey(seed.getBytes());

byte[] enc = toByte(encrypted);

byte[] result = decrypt(rawKey, enc);

return new String(result);

} catch (Exception e) {

e.printStackTrace();

}

}

return null;

}

3:用法:

public void setStringPrefSec(String sKey, String sValue){

SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFER_FILE, 0);

Editor edit = pref.edit();

edit.putString(sKey, encryption.encrypt(getUUID(), sValue));

edit.commit();

}

public String getStringPrefSec(String sKey, String sDefaultV){

SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFER_FILE, 0);

String sTemp = pref.getString(sKey, encryption.encrypt(getUUID(), sDefaultV));

sTemp = encryption.decrypt(getUUID(), sTemp);

return sTemp;

}

4:效果:

Dance In Wind

23.4.2013

你可能感兴趣的:(android基础)