Monday, November 28, 2011

How to encrypt a serializable class in Android

public boolean save(YourClass pref){
boolean isSuccess = false;
try {
final File persistedFile = new File("/sdcard/sr.dat");
if(persistedFile.exists())
persistedFile.delete();
OutputStream file = new FileOutputStream(persistedFile);
BufferedOutputStream buffer = new BufferedOutputStream(file);
Cipher desCipher = getCipher(Cipher.ENCRYPT_MODE);
CipherOutputStream cos = new CipherOutputStream(buffer, desCipher);
ObjectOutputStream oos = new ObjectOutputStream(cos);
oos.writeObject(pref);
oos.flush();
oos.close();
} catch (IOException ex) {
Log.d(TAG, ex.getMessage());
isSuccess = false;
} catch (InvalidKeyException e) {
Log.d(TAG, e.getMessage());
isSuccess = false;
} catch (InvalidKeySpecException e) {
Log.d(TAG, e.getMessage());
isSuccess = false;
} catch (NoSuchAlgorithmException e) {
Log.d(TAG, e.getMessage());
isSuccess = false;
} catch (NoSuchPaddingException e) {
Log.d(TAG, e.getMessage());
isSuccess = false;
}
return isSuccess;
}
private Cipher getCipher(int opmode) throws InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException {
byte key[] = "Aruna Tennakoon".getBytes();
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

// Create Cipher
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(opmode, secretKey);
return desCipher;
}
public Preference load(){
Preference repo = null;
try {

final File persistedFile = File("/sdcard/sr.dat");
if(!persistedFile.exists()) {
// sr is not created yet. Create one and return
return;
}
Cipher desCipher = getCipher(Cipher.DECRYPT_MODE);
FileInputStream fis = new FileInputStream(persistedFile.getAbsolutePath());
BufferedInputStream bis = new BufferedInputStream(fis);
CipherInputStream cis = new CipherInputStream(bis, desCipher);
ObjectInputStream ois = new ObjectInputStream(cis);
repo = (YourClass) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
Log.d(TAG, e.getMessage());
} catch (StreamCorruptedException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
} catch (InvalidKeyException e) {
Log.d(TAG, e.getMessage());
} catch (InvalidKeySpecException e) {
Log.d(TAG, e.getMessage());
} catch (NoSuchAlgorithmException e) {
Log.d(TAG, e.getMessage());
} catch (NoSuchPaddingException e) {
Log.d(TAG, e.getMessage());
} catch (ClassNotFoundException e) {
Log.d(TAG, e.printStackTrace());
}

return repo;
}

1 comment:

  1. Under what namespace is the Cipher class?
    Eclipse can't recognize it.

    ReplyDelete