public String crypt(int mode, String encryption_subject) throws CryptException { final PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(SALT, 20); final SecretKeyFactory kf = getSecretKeyFactory(); final SecretKey k = getSecretKey(kf); final Cipher crypter = getCipherInstance(); String result; switch(mode){ case Cipher.DECRYPT_MODE: initialise(ps, k, crypter, Cipher.DECRYPT_MODE); result = getString(encryption_subject, crypter); break; case Cipher.ENCRYPT_MODE: default: initialise(ps, k, crypter, Cipher.ENCRYPT_MODE); result = encode(encryption_subject, crypter); } return result; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String hash = transform(SECRET_PASSWORD_TO_ENCRYPT, Cipher.ENCRYPT_MODE); ((TextView)findViewById(R.id.txt_encrypted)).setText(hash); ((TextView)findViewById(R.id.txt_unencrypted)).setText(transform(hash, Cipher.DECRYPT_MODE)); }
private String getString(String encryption_subject, Cipher crypter) throws CryptException { try { return new String(finishTransformation(crypter, getDecode(encryption_subject)), CHARSET); } catch (UnsupportedEncodingException e) { throw new CryptException(e); } }
String transform(String var, int transformationType) { String passwordHashed = ""; try { passwordHashed = crypt(transformationType, var); } catch (CryptException e) { if (transformationType == Cipher.ENCRYPT_MODE) { Log.e(TAG, "A problem during the encryption has occurred", e); passwordHashed = ""; } if (transformationType == Cipher.DECRYPT_MODE) { Log.e(TAG, "A problem during the decryption has occurred:", e); } } return passwordHashed; }
private String encode(String encryption_subject, Cipher crypter) throws CryptException { try { return Base64.encode(finishTransformation(crypter, encryption_subject.getBytes(CHARSET))); } catch (UnsupportedEncodingException e) { throw new CryptException(e); } }