Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For those who wish to use String and Base64-encoding for usage with a database you can use these (slightly rewritten) functions from Mike Keskinov (and xalien on Anddev.org).</p> <pre><code>public String encrypt(String str) { try { // Encode the string into bytes using utf-8 byte[] utf8 = str.getBytes("UTF8"); // Encrypt byte[] enc = ecipher.doFinal(utf8); // Encode bytes to base64 to get a string return new String(Base64.encode(enc,0)); } catch (BadPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } return null; } public String decrypt(String str) { try { // Decode base64 to get bytes byte[] dec = Base64.decode(str, 0); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 return new String(utf8, "UTF8"); } catch (BadPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } return null; } </code></pre> <p>This code also uses the built-in Android Base64 libraries, so no need for importing any additional external libraries.</p> <p>Something I didn't realise at first was how to actually use this class from another class (my ignorance). Here's a simple example:</p> <pre><code>StringEncrypter se = new StringEncrypter("mypass"); String decryptedString = se.decrypt(encryptedString); </code></pre> <p>One more thing on Base64. I found out the hard way that Base64 encoding adds a '/n' linefeed character (0x0a) whenever the string gets longer than 76 characters. This severely messes up the decrypt results. To strip out these newline characters you can add something like:</p> <pre><code>b64_enc_str = se.encrypt(plaintext_str); str = b64_enc_str.replace("/n",""); </code></pre> <p>Hopefully it helps someone.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload