Android–Encryption Made Easy


I am giving you following class that you can embed in your code to encrypt and decrypt. You just need to put a PASSWORD to call its init( ) method.

import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class Encryption {
    // related links
    // PBEWithMD5AndDES
    private static final String INSTANCE = "PBEWithSHA256And256BitAES-CBC-BC";
    private static final String TAG = "Encryption";
    private static final int SALT_LENGTH     = 10;
    private static final int SALT_ITERATIONS = 10;
    private static SecretKey secretKey;
    public static CipherOutputStream encryptionWrap(OutputStream os) {
        try {
            final byte salt[] = new byte[SALT_LENGTH];
            new; // @TEMP
            PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, SALT_ITERATIONS);
            Cipher c = Cipher.getInstance(INSTANCE);
            c.init(Cipher.ENCRYPT_MODE, secretKey, pbeParamSpec);
            return new CipherOutputStream(os, c);
        } catch (Exception e) {
            OpenFeintInternal.log(TAG, e.getMessage());
        return null;
    public static CipherInputStream decryptionWrap(InputStream is) {
        try {
            final byte salt[] = new byte[SALT_LENGTH];
            if ( != SALT_LENGTH) throw new Exception("Couldn't read entire salt");
            PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, SALT_ITERATIONS);
            Cipher c = Cipher.getInstance(INSTANCE);
            c.init(Cipher.DECRYPT_MODE, secretKey, pbeParamSpec);
            return new CipherInputStream(is, c);
        } catch (Exception e) {
            OpenFeintInternal.log(TAG, e.getMessage());
        return null;
     * if init return false, then this platform does not support
     * secure data store. then can't not use ofx
    public static boolean init(String password) {
        try {
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory keyFac = SecretKeyFactory.getInstance(INSTANCE);
            secretKey = keyFac.generateSecret(pbeKeySpec);
            // try to make an encrypter and decrypter to see if it works.
            byte testString[] = INSTANCE.getBytes(); // just write the name of the cipher we're using
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            CipherOutputStream cos = encryptionWrap(baos);
            final byte[] encryptedContents = baos.toByteArray();
            if (encryptedContents.length == 0) throw new Exception();
            CipherInputStream cis = decryptionWrap(new ByteArrayInputStream(encryptedContents));
            byte decryptedContents[] = Util.toByteArray(cis);
            if (!Arrays.equals(decryptedContents, testString)) throw new Exception();
        } catch (Exception e) {
            secretKey = null;
            return false;
        return true;
    public static boolean initialized() {
        return secretKey != null;
    public static InputStream decrypt(File file) throws FileNotFoundException {
        return decryptionWrap(new FileInputStream(file));
    public static byte[] decryptFile(String path) throws FileNotFoundException, IOException {
        return Util.toByteArray(decrypt(new File(path)));
    public static byte[] decrypt(byte input[]) {
        try {
            return Util.toByteArray(decryptionWrap(new ByteArrayInputStream(input)));
        } catch (Exception e) {
            return null;
    public static boolean encrypt(byte[] in, String path) {
        try {
            OutputStream os = encrypt(path);
            return true;
        } catch (Exception e) {
            // @TODO cleanup?
        return false;
    public static OutputStream encrypt(String path) throws FileNotFoundException {
        return encryptionWrap(new FileOutputStream(new File(path)));
    public static byte[] encrypt(byte input[]) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final CipherOutputStream enc = encryptionWrap(baos);
            return baos.toByteArray();
        } catch (Exception e) {
            return null;


if (!Encryption.initialized()) {


InputStream inn = Encryption.decryptionWrap(is);


android, java, encryption, secret key factory problems solved,


  1. Your style is very unique in comparison to other folks I've read stuff from. Thank you for posting when you have the opportunity, Guess I'll just
    book mark this blog.

    Here is my blog - more
    Also see my page: see more

  2. I've been exploring for a little bit for any high-quality articles or weblog posts on this kind of space . Exploring in Yahoo I finally stumbled upon this site. Reading this info So i'm satisfied to exhibit that
    I've an incredibly just right uncanny feeling I came upon just what I needed. I most definitely will make certain to don?t forget this site and provides it a look on a relentless basis.

    Also visit my blog: for bio HotRebbecca

  3. I used to be recommended this website by means of my cousin.
    I'm not sure whether this put up is written by means of him as nobody else know such particular approximately my difficulty. You're incredible!

    Here is my page - Visit Website

  4. I seriously love your blog.. Very nice colors & theme.
    Did you develop this website yourself? Please reply back as I'm planning to create my own site and would like to learn where you got this from or just what the theme is named. Thank you!

    my blog post :: visit website

  5. I am really thankful to the owner of this website who has shared this great paragraph at here.

    Stop by my site - Visit Website

  6. I believe everything composed was actually very logical. But, what about this?
    what if you added a little information? I mean, I don't want to tell you how to run your website, but suppose you added a headline to maybe grab people's attention?
    I mean "Android-Encryption Made Easy" is kinda plain.
    You ought to look at Yahoo's front page and see how they create post titles to grab viewers to click. You might add a video or a related picture or two to grab people excited about everything've got to say.

    In my opinion, it might bring your posts
    a little bit more interesting.

    my blog post a grants

  7. Thanks for sharing your info. I really appreciate your efforts and I am waiting for your next write ups
    thank you once again.

    my web site ...

  8. Greetings from Carolina! I'm bored at work so I decided to check out your website on my iphone during lunch break. I love the info you provide here and can't wait to take a
    look when I get home. I'm surprised at how fast your blog loaded on my mobile .. I'm not even using WIFI, just 3G .
    . Anyways, very good site!

    Here is my blog: see more

  9. It's difficult to find knowledgeable people in this particular subject, but you seem like you know what you're talking about!


    Also visit my website:

  10. It's difficult to find knowledgeable people in this particular subject, but you seem like you know what you're talking about!

    Take a look at my site:

  11. Write more, thats all I have to say. Literally, it seems as though you relied on the
    video to make your point. You definitely know what youre talking about, why waste your intelligence on just posting videos to your site when you
    could be giving us something informative to read?

    my page website

  12. Hey There. I discovered your blog using msn.
    That is a very smartly written article. I'll be sure to bookmark it and return to learn more of your helpful info. Thanks for the post. I'll definitely comeback.

    Here is my blog ... in grants

  13. You need to take part in a contest for one of the most useful
    blogs on the internet. I'm going to recommend this blog!

    Here is my page :: see more

  14. I all the time used to study piece of writing in news papers but now
    as I am a user of net so from now I am using net for articles, thanks to web.

    Feel free to surf to my webpage - Visit

  15. Wonderful article! That is the kind of info that should be shared around the web.
    Shame on Google for not positioning this post upper!
    Come on over and visit my site . Thanks =)

    Look at my web page; see more

  16. I'm not sure why but this site is loading incredibly slow for me. Is anyone else having this issue or is it a issue on my end? I'll check back later on
    and see if the problem still exists.

    Also visit my web site

  17. Greetings from Idaho! I'm bored to tears at work so I decided to check out your site on my iphone during lunch break. I love the info you provide here and can't wait
    to take a look when I get home. I'm surprised at how fast your blog loaded on my phone .. I'm
    not even using WIFI, just 3G .. Anyways, excellent site!

    Also visit my blog :: with Teen Gangbangs

  18. Appreciation to my father who stated to me about this website,
    this blog is genuinely awesome.

    My homepage visit

  19. Hi there! I could have sworn I've been to this blog before but after reading through some of the post I realized it's
    new to me. Anyhow, I'm definitely glad I found it and I'll be
    book-marking and checking back frequently!

    My web page - more

  20. Right now it sounds like Expression Engine is the preferred blogging platform available right now.
    (from what I've read) Is that what you are using on your blog?

    Here is my web site:

  21. you are in reality a good webmaster. The web site loading speed is incredible.
    It kind of feels that you are doing any unique trick.
    Furthermore, The contents are masterwork.
    you've performed a fantastic activity on this subject!

    my website: Email Console

  22. I blog frequently and I seriously thank you for your content.
    Your article has really peaked my interest. I am going
    to bookmark your website and keep checking for new information about once a week.

    I subscribed to your RSS feed as well.

    Here is my web-site: such as Tori Rubs Down With Baby Oil For Bottle Insertion And 65533 10112011

  23. Fοr most recent іnfοrmation you hаve
    tο go to ѕee woгlԁ
    ωide web anԁ on world-wіde-web I found this web page as a most eхcellent site for newеst updates.

    Look at my web site raspberry ketone uk

  24. Why visitors still make use of to read news papers when in this technological world everything is available on net?

    Here is my page; No Gravatar

  25. Hey! I know this is kinda off topic but I'd figured I'd
    ask. Would you be interested in trading links or maybe guest writing a
    blog article or vice-versa? My site covers a lot of the same subjects as yours
    and I think we could greatly benefit from each other. If you're interested feel free to send me an e-mail. I look forward to hearing from you! Superb blog by the way!

    Take a look at my website ::

  26. Hello there, You've done a great job. I will definitely digg it and personally suggest to my friends. I am confident they'll be benefited from this site.

    my web site; 1

  27. Hello! Quіck queѕtіon
    that's totally off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my apple iphone. I'm trying to find a template or ρlugіn that might be аblе to fix this issuе.
    If уou have any suggestіons, please share.
    Many thanks!

    Alѕο visit my ωeb-site :: vitamin shoppe coupon

  28. I alwayѕ emailed this website post ρagе to all my cοntactѕ,
    as if liκe to read it afterwаrԁ my friends will

    Vіѕіt my wеblоg ::
    vistaprint coupon

  29. Excellent post! We are linking to this particularly great content
    on our site. Keep up the great writing. - ageless male - ageless male

    My web site; ageless male

  30. Hi, I want to subscribe for this blog to take newest updates, thus where can i do it please

    Feel free to surf to my web page ... 그리고 성숙 - 김창옥 서울여대 겸임교수

  31. Inspiring story there. What occurred after? Thanks!

    Here is my web page; HTTP://

  32. Oh my goodness! Awesome article dude! Thanks, However I am
    experiencing troubles with your RSS. I don't know the reason why I am unable to join it. Is there anybody else having the same RSS issues? Anyone that knows the answer will you kindly respond? Thanx!!

    My blog post world Chat Room

  33. I've been exploring for a bit for any high quality articles or blog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this web site. Reading this info So i'm satisfied to show that I've an incredibly just right uncanny feeling I came upon exactly what I needed. I so much for sure will make sure to do not put out of your mind this web site and provides it a look on a constant basis.

    Look into my site -

  34. I have read a few excellent stuff here. Certainly worth bookmarking for revisiting.

    I surprise how a lot effort you set to create this sort of fantastic informative website.

    My weblog;

  35. Hey there! This post could not be written any better!
    Reading through this post reminds me of my good old room mate!

    He always kept talking about this. I will forward this article to him.
    Fairly certain he will have a good read. Thank you for sharing!

    Feel free to visit my blog post How Can I lose weight

  36. Thanks for finally talking about > "Android-Encryption Made Easy" < Loved it!

    Look into my blog; Diet

  37. Hello! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up
    losing a few months of hard work due to no backup. Do you have
    any solutions to protect against hackers?

    Here is my blog post:

  38. If you want to increase your familiarity only keep visiting
    this web page and be updated with the most recent information posted here.

    my weblog; the particular disc produced both variety of hormones

  39. Wow, this article is nice, my younger sister is analyzing such
    things, so I am going to inform her.

    Feel free to visit my webpage

  40. You've made some good points there. I checked on the web for additional information about the issue and found most individuals will go along with your views on this site.

    Feel free to surf to my blog ...

  41. Heya i am for the first time here. I came across this board and I
    find It really useful & it helped me out a lot. I hope to give something back and aid others like you aided me.

    Here is my web blog:

  42. This is a good tip particularly to those fresh to
    the blogosphere. Simple but very accurate information… Thanks for sharing this one.

    A must read article!

    my weblog - playful brunette teen

  43. I think the admin of this web site is actually
    working hard in support of his site, because here every
    material is quality based information.

    Stop by my blog; at porno website

  44. These men have all entered the Manu background books for what they brought into the game
    at this prestige club. That is suitable, League of Legends is a hundred% cost-free.

    Also incorporated with this data is often a whole record with the various
    crops, alongside with fees, sale price tag,
    quantity it truly is easily out there and maturity time neatly affreux
    out inside a desk.

    Here is my weblog - League Of Legends Hack

  45. Hello There. I discovered your blog the use of msn.
    That is a very well written article. I will be sure to bookmark it and
    come back to read extra of your helpful info. Thanks for the post.
    I'll definitely return.

    my website; That Guy

  46. I usually do not drop many comments, however I browsed through a few responses on "Android-Encryption Made Easy".
    I actually do have a couple of questions for
    you if it's allright. Could it be only me or do a few of these comments appear like they are written by brain dead people? :-P And, if you are writing on additional online sites, I would like to keep up with you. Would you make a list of every one of your social networking pages like your linkedin profile, Facebook page or twitter feed?

    Feel free to visit my blog Ambers ***** dripping ***** 3312006

  47. Ahaa, its pleasant discussion on the topic of this piece of writing here at this web site, I have read
    all that, so now me also commenting at this place.

    Look into my web-site;

  48. Hi! Do you know if they make any plugins to help with SEO?
    I'm trying to get my blog to rank for some targeted keywords but I'm
    not seeing very good results. If you know of any please share.

    Here is my blog a fantastic read

  49. Hey just wanted to give you a quick heads up. The words in your content seem
    to be running off the screen in Internet explorer. I'm not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I'd post to let you
    know. The design look great though! Hope you get the issue solved soon.

    my site - visit website

  50. I have to thank you for the efforts you have put in writing this website.

    I'm hoping to check out the same high-grade content by you in the future as well. In fact, your creative writing abilities has motivated me to get my own, personal site now ;)

    Also visit my homepage: his explanation

  51. An educational toy store offers plenty of opportunities.
    New model vehicles will generally have more information than older models due to the inefficiency in charging processor.
    To power up an electric car makes sense, whichever way
    you view it. Working of Modern Flying used motorcyclesThough we commonly use 'flying used motorcycles' and 'roadable aircraft' as synonyms,
    they have issued some auction rules and information regarding the B.

    Look into my blog post - used cars value []

  52. Amazing! This blog looks just like my old one! It's on a totally different subject but it has pretty much the same layout and design. Outstanding choice of colors!

    Here is my web site

  53. Appreciate the recommendation. Will try it out.

    Check out my blog - see more