AES encryption on Android


Buddha Gabriel

I have to encrypt and decrypt text on android device. I found some solutions, but when I encrypt the text again, the result is different. Can anyone tell me why?

Here is my code:

public class AESDemo {


    private static final String password = "test";
    private static String salt;
    private static int pswdIterations = 65536;
    private static int keySize = 256;
    private byte[] ivBytes;

    public String encrypt(String plainText) throws Exception {

        //get salt
        salt = generateSalt();
        byte[] saltBytes = salt.getBytes("UTF-8");

        // Derive the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(
                password.toCharArray(),
                saltBytes,
                //null,
                pswdIterations,
                keySize
        );

        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        //encrypt the message
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        //return new Base64().encodeAsString(encryptedTextBytes);
        return  Base64.encodeToString(encryptedTextBytes, Base64.DEFAULT);
    }

    @SuppressWarnings("static-access")
    public String decrypt(String encryptedText) throws Exception {

        byte[] saltBytes = salt.getBytes("UTF-8");
        //byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);
        byte[] encryptedTextBytes= Base64.decode(encryptedText, Base64.DEFAULT);

        // Derive the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(
                password.toCharArray(),
                saltBytes,
                pswdIterations,
                keySize
        );

        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        // Decrypt the message
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));


        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return new String(decryptedTextBytes);
    }

    public String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        String ss = "";
        random.nextBytes(bytes);
        String s = new String(bytes);
        return "sare";
    }
}

I've hardcoded the salt to be the same, but the result is different each time. Can anyone tell me why?

Marek Pola

Your IV fluids confuse me. You call getIV(), but where do you actually set the IV for encryption? It seems to me that you are using a random IV, which might explain why you are getting different encrypted data each time.

I suggest trying to create a dynamic IvParameterSpec class and populate it with a preset IV.

Related


Implementing AES encryption in Android

MSR I found this Java AES encryption on the internet. Can I modify and use this Java code in an Android application? Actually I don't know if it will fit my android device. If it can be used, does it mean that this Java code can be modified? import java.io.Uns

AES encryption test (android)

Sergey 136 I have developed an encryption program for Android that uses a symmetric key to encrypt and decrypt data (AES algorithm). So I was asked to verify that not only does reverse engineering work, but also that the data can be decrypted using only one ke

AES encryption testing (android)

sergey136 I have developed an encryption program for android which is using a symmetric key to both encrypt and decrypt the data (AES algorithm). So I have been asked to verify that not only a reverse engineering is working correctly but also that only one key

Implementing AES encryption in Android

MSR I found this Java AES encryption on the internet. Can I modify and use this Java code in an Android application? Actually I don't know if it will fit my android device. If it can be used, does it mean that this Java code can be modified? import java.io.Uns

Android AES encryption key

David R. I am developing an android application and I want to use AES-128 for encryption. I use hex for the key and text. I use this website: http://testprotect.com/appendix/AEScalc , calculate the AES encryption with the following key: "c4dcc3c6ce0acaec4327b6

Android Java AES encryption

Bright I'm currently developing an Android app that includes encrypting a string using AES. But for some reason my app doesn't decrypt correctly. I tried to change the Base64 format but couldn't solve it. The code is similar to the Android Cryptography example

Android encryption/decryption using AES

h4rd4r7c0r3: Is there a good example of how to encrypt and decrypt images and other files using AES on Android ? Nacho L.: Warning: this answer contains code you shouldn't use because it's not secure (use SHA1PRNG for key derivation, and use AES in ECB mode) I

.NET AES encryption and Android decryption

Daniel Warding I am using the following code to encrypt a GUID string using AES in .NET. // Decode the challenge bytes from base 64 byte[] challengeBytes = Base64.decode(challenge, Base64.NO_WRAP); ICryptoTransform encryptor = aes.Crea

Android encryption/decryption using AES

h4rd4r7c0r3: Is there a good example of how to encrypt and decrypt images and other files using AES on Android ? Nacho L.: Warning: this answer contains code that you shouldn't use because it's not secure (use SHA1PRNG for key derivation, and use AES in ECB mo

Improve the speed of encryption AES Android

Flo354 I have developed an android application for encrypting files on my phone. By searching, I found this thread: How to encrypt files from SD card using AES in Android? The method works fine, but encrypting the file is very slow... in this line: byte[] d =

Improve the speed of encryption AES Android

Flo354 I have developed an android application for encrypting files on my phone. By searching, I found this thread: How to encrypt files from SD card using AES in Android? The method works fine, but encrypting the file is very slow... in this line: byte[] d =

.NET AES encryption and Android decryption

Daniel Warding I am using the following code to encrypt a GUID string using AES in .NET. // Decode the challenge bytes from base 64 byte[] challengeBytes = Base64.decode(challenge, Base64.NO_WRAP); ICryptoTransform encryptor = aes.Crea

Android encryption/decryption using AES

h4rd4r7c0r3: Is there a good example of how to encrypt and decrypt images and other files using AES on Android ? Nacho L.: Warning: this answer contains code you shouldn't use because it's not secure (use SHA1PRNG for key derivation, and use AES in ECB mode) I

AES encryption and decryption algorithm in Android

username I am trying to encrypt and decrypt my data using AES algorithm in Android. this is my code package com.example.aesandroidsecurity; import java.security.NoSuchAlgorithmException; //import java.security.spec.AlgorithmParameterSpec; impor

AES encryption for iOS and Android (UINT not in Java)

Eric: all, I'm new to crypto, so I don't know all the info I need to share to get help; but it's good that I know more about how to ask this question, and I'll revise the question :) I have AES encryption in both iOS and Android apps delivered to the device vi

AES encryption for iOS and Android (UINT not in Java)

Eric: all, I'm new to crypto so I don't know all the info I need to share to get help; but it's good that I know more about how to ask this question and I'll revise the question :) I have AES encryption in both iOS and Android apps delivered to the device via

AES encryption/decryption from Android to server

Berhag I have a server and two clients. The server runs Java and Jersey (Rest). One client is a Java client and the other is an Android client. I want to send a message encrypted with AES. So I have the following code (on server and client): cipher = Cipher.ge

AES encryption in android and decryption in php and vice versa

Pihu I am trying to learn AES by testing my code against https://aesencryption.net . I've had a bug before and also . So I somehow manipulated the Base64 to resolve the error. I think, now in my application the text is encrypted and decrypted correctly. Howeve

AES encryption in Android and decryption in Node.js

Nelson Joseph: I am trying to encrypt in android and decrypt in nodejs server. I generated an AES 128 bit key, encrypted it using the AES algorithm, then encrypted this generated key using the RSA algorithm. Then send both to the server. But when decrypting on

AES encryption in android and decryption in php and vice versa

Pihu I am trying to learn AES by testing my code against https://aesencryption.net . I've had a bug before and also . So I somehow manipulated the Base64 to resolve the error. I think, now in my application the text is encrypted and decrypted correctly. Howeve

AES encryption in android and decryption in php and vice versa

Pihu I am trying to learn AES by testing my code against https://aesencryption.net . I've had a bug before and also . So I somehow manipulated the Base64 to resolve the error. I think, now in my application the text is encrypted and decrypted correctly. Howeve

AES encryption in android and decryption in php and vice versa

Pihu I am trying to learn AES by testing my code against https://aesencryption.net . I've had a bug before and also . So I somehow manipulated the Base64 to resolve the error. I think, now in my application the text is encrypted and decrypted correctly. Howeve

Android log encryption using AES and RSA

Akinka Patil I want to mail encrypted log files from my application. Since the log can be larger, I encrypt the data with AES and encrypt the key with RSA. Since the AES key is required to decrypt the logs, I will send the encrypted key and log in the same fil

AES encryption/decryption from Android to server

Berhag I have a server and two clients. The server runs Java and Jersey (Rest). One client is a Java client and the other is an Android client. I want to send a message encrypted with AES. So I have the following code (on server and client): cipher = Cipher.ge

AES encryption for iOS and Android (UINT not in Java)

Eric: all, I'm new to crypto, so I don't know all the info I need to share to get help; but it's good that I know more about how to ask this question, and I'll revise the question :) I have AES encryption in both iOS and Android apps delivered to the device vi

AES encryption on android device and .Net server

McBurgl I am new to the field of cryptography. Excuse me if this is a basic requirement. On the Android side, I'm trying to encrypt using the following code snippet: // Get the salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[s

Android AES encryption from C# to Java

NovusMobile I am converting C# encryption code to Android. The problem I'm having is not being able to encrypt text like C#. Below I copy-pasted both codes. Both are about using it with valid code, you can use any password and any plain text. You will find tha

AES encryption/decryption from Android to server

BerHug I have a server and two clients. The server runs Java and Jersey (Rest). One client is a Java client and the other is an Android client. I want to send a message encrypted with AES. So I have the following code (on server and client): cipher = Cipher.ge

AES encryption in Android and decryption in Node.js

Nelson Joseph: I am trying to encrypt in android and decrypt in nodejs server. I generated an AES 128 bit key, encrypted it using the AES algorithm, then encrypted this generated key using the RSA algorithm. Then send both to the server. But when decrypting on