Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android encrypting plaint text using facebook conceal library

I tried to encrypt plaintext using the below code. The code seems encrypt the text but it doesnt decrypt to plaintext back. What am I doing wrong ?

The code:

Entity entity = new Entity("password");
byte[] ciphertext = crypto.encrypt(("data to encrypt").getBytes(),entity);
plaintext = crypto.decrypt(ciphertext,entity)

Output:

Ecrypted text:[B@417a110
Decrypted text:[B@417df20
like image 259
kirron s Avatar asked May 24 '15 05:05

kirron s


1 Answers

The following code can encrypt/decrypt string

KeyChain keyChain = new SharedPrefsBackedKeyChain(context, CryptoConfig.KEY_256);
crypto = AndroidConceal.get().createDefaultCrypto(keyChain);

public static String encrypt(String key, String value) throws KeyChainException, CryptoInitializationException, IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    OutputStream cryptoStream = crypto.getCipherOutputStream(bout, Entity.create(key));
    cryptoStream.write(value.getBytes("UTF-8"));
    cryptoStream.close();
    String result = Base64.encodeToString(bout.toByteArray(), Base64.DEFAULT);
    bout.close();
    return result;
}

public static String decrypt(String key, String value) throws KeyChainException, CryptoInitializationException, IOException {
    ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(value, Base64.DEFAULT));
    InputStream cryptoStream = crypto.getCipherInputStream(bin, Entity.create(key));
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    int read = 0;
    byte[] buffer = new byte[1024];
    while ((read = cryptoStream.read(buffer)) != -1) {
        bout.write(buffer, 0, read);
    }
    cryptoStream.close();
    String result = new String(bout.toByteArray(), "UTF-8");
    bin.close();
    bout.close();
    return result;
}
like image 152
Desmond Lua Avatar answered Oct 13 '22 06:10

Desmond Lua