Tuesday, 2 December 2014

HB Blog 41: Encryption And Decryption Process Of String.

In cryptography, encryption is the process of encoding messages or information in such a way that only authorized parties can read it. Encryption does not of itself prevent interception, but denies the message content to the interceptor.
In cryptography, decryption is the process of decoding messages or information that has been encrypted.Decryption requires a secret key or password.

Have a look on few code snippets,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Original text
        String originalText = "This is my text - Harshal Benake";
        System.out.println("[ORIGINAL]:" + originalText);
        // Set up secret key spec for 128-bit AES encryption and decryption
        SecretKeySpec secretKeySpec = null;
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed("any data used as random seed".getBytes());
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128, secureRandom);
            secretKeySpec = new SecretKeySpec((keyGenerator.generateKey()).getEncoded(), "AES");
        } catch (Exception e) {
            Log.e(TAG, "AES secret key spec error");
        }
        // Encode the original data with AES
        byte[] encodedBytes = null;
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            encodedBytes = cipher.doFinal(originalText.getBytes());
        } catch (Exception e) {
            Log.e(TAG, "AES encryption error");
        }
        System.out.println("[ENCODED]:" + Base64.encodeToString(encodedBytes, Base64.DEFAULT));
        // Decode the encoded data with AES
        byte[] decodedBytes = null;
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            decodedBytes = cipher.doFinal(encodedBytes);
        } catch (Exception e) {
            Log.e(TAG, "AES decryption error");
        }
        System.out.println("[DECODED]:" + new String(decodedBytes));

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File

No comments:

Post a Comment