Java tutorial
//package com.java2s; import android.util.Log; import javax.crypto.Cipher; public class Main { private static final String LOG_TAG = "MarvinMessaging"; public static Cipher storageEncryptionCipher; public static String encryptText(CharSequence plaintext) { return encryptText(fromCharSeqToChars(plaintext), storageEncryptionCipher); } public static String encryptText(char[] plaintext) { return encryptText(plaintext, storageEncryptionCipher); } private static String encryptText(char[] plaintext, Cipher cipher) { byte[] plaintextBytes = charArrayToByteArray(plaintext); byte[] ciphertext = {}; try { ciphertext = cipher.doFinal(plaintextBytes); } catch (Exception e) { Log.d(LOG_TAG, "encryptText", e); } //turn into hex so storage as a string is possible (db) return toHexString(ciphertext); } /** * we can't store a password as a string, since in Java * strings are immutable, and thus we can't null out and * guarantee the password doesn't hang around after GC; * CharSequence doesn't have this problem, and that's what * an EditText returns; So, we go from CharSequence to * an array of bytes; We want a byte array anyway, for crypto. * */ public static char[] fromCharSeqToChars(CharSequence seq) { char[] ret = new char[seq.length()]; int i; for (i = 0; i < seq.length(); i++) { ret[i] = seq.charAt(i); } return ret; } public static byte[] charArrayToByteArray(char[] in) { byte[] ret = new byte[in.length]; int i; for (i = 0; i < in.length; i++) { ret[i] = (byte) (in[i] & 0xFF); } return ret; } public static String toHexString(byte bytes[]) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < bytes.length; ++i) { buf.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF)).substring(1)); } return buf.toString(); } }