Android: AES encryption and decryption using GCM mode in Android?


Uday

I am trying to encrypt and decrypt a string using AES algorithm and GCM mode.

My code is able to encrypt the string but not able to decrypt the encoded data.

Steps to follow:

  • createkey()
  • encrypted (string)
  • decrypt(encded_data);

my code:

build key

public void createKey() {
    try {
        if (!ks.containsAlias(keyName)) {

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                Log.e("MAinAcvtivity", "Current version is 23(MashMello)");
                //Api level 23
                KeyGenerator generator  = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
                generator.init(
                        new KeyGenParameterSpec.Builder(keyName,
                                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                                .build());
                SecretKey key = generator.generateKey();

            } else {
                Log.e("MAinAcvtivity", "Current version is < 23(MashMello)");

            }

        }else{
            Log.e("MAinAcvtivity", "Key exist");
        }
    } catch (Exception e) {

        Log.e("MAinAcvtivity", "Key didn't generated");
        Log.e("MAinAcvtivity", Log.getStackTraceString(e));
    }
}

Encryption:

public String doEncryption(String data) {
    try {

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            ce = Cipher.getInstance("AES/GCM/NoPadding");
            sKey = (SecretKey) ks.getKey(keyName, null);
            ce.init(Cipher.ENCRYPT_MODE, sKey);
        } else {

        }

        encodedData = ce.doFinal(data.getBytes());
        mEncodedData = Base64.encodeToString(encodedData, Base64.DEFAULT);
    } catch (Exception e) {
        Log.e("Main", "RSA Encription Error.!");
        Log.e("MainActivity", "RSA Decryption Error.!", e);
    }
    Log.e("Main", "encripted DATA =" + mEncodedData);
    return mEncodedData;
}

Decrypt:

public String doDecryption(String eData) {
    String decryptedText = null;
encodedData = Base64.decode(eData, Base64.DEFAULT);

    try {
        Cipher c;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Log.i("MainActivity","in Decryption version m");

            c = Cipher.getInstance("AES/GCM/NoPadding");
            sKey = (SecretKey) ks.getKey(keyName, null);
            Log.e("MainActivity", "After getting key : " );
            c.init(Cipher.DECRYPT_MODE, sKey);
        } else {

        }

        decodedData = c.doFinal(encodedData);
        decryptedText = new String(decodedData, "UTF-8");
        Log.e("MainActivity", "After decryption : "+ decryptedText);
    } catch (Exception e) {
        Log.e("MainActivity", "RSA Decryption Error.!", e);
    }
    return decryptedText;
}

Error log:

MAinAcvtivity: Key exist
Main: encripted DATA =KrHmMXhcytb0owDzLaMY2wsQmwY=
MainActivity: in decryption : encoded data =KrHmMXhcytb0owDzLaMY2wsQmwY=
MainActivity: After getting key : 
MainActivity: RSA Decryption Error.!
MainActivity: java.security.InvalidKeyException: IV required when     decrypting. Use IvParameterSpec or AlgorithmParameters to provide it.
MainActivity:     at android.security.keystore.AndroidKeyStoreAuthenticatedAESCipherSpi$GCM.initAlgorithmSpecificParameters(AndroidKeyStoreAuthenticatedAESCipherSpi.java:79)
MainActivity:     at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:106)
Uday

bingo

I found a solution.

In decrypt I made the following changes:

 GCMParameterSpec spec = new GCMParameterSpec(128,ce.getIV());
 c.init(Cipher.DECRYPT_MODE, sKey,spec);

Related


Android: AES encryption and decryption using GCM mode in Android?

Uday I am trying to encrypt and decrypt a string using AES algorithm and GCM mode. My code is able to encrypt the string, but I am not able to decrypt the encoded data. Steps to follow: createkey() encrypted (string) decrypt(encded_data); my code: build key pu

Android: AES encryption and decryption using GCM mode in Android?

Uday I am trying to encrypt and decrypt a string using AES algorithm and GCM mode. My code is able to encrypt the string but not able to decrypt the encoded data. Steps to follow: createkey() encrypted (string) decrypt(encded_data); my code: build key public v

Android: AES encryption and decryption using GCM mode in Android?

Uday I am trying to encrypt and decrypt a string using AES algorithm and GCM mode. My code is able to encrypt the string, but I am not able to decrypt the encoded data. Steps to follow: createkey() encrypted (string) decrypt(encded_data); my code: build key pu

Android: AES encryption and decryption using GCM mode in Android?

Uday I am trying to encrypt and decrypt a string using AES algorithm and GCM mode. My code is able to encrypt the string, but I am not able to decrypt the encoded data. Steps to follow: createkey() encrypted (string) decrypt(encded_data); my code: build key pu

Android: AES encryption and decryption using GCM mode in Android?

Uday I am trying to encrypt and decrypt a string using AES algorithm and GCM mode. My code is able to encrypt the string, but I am not able to decrypt the encoded data. Steps to follow: createkey() encrypted (string) decrypt(encded_data); my code: build key pu

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

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

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

.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

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 gcm encryption and decryption interworking

Prajwal Please share the working code of encryption in node js and decryption in java AES/GCM/NoPadding In node js : function createCipherCommon(text, alg, key, iv) { var cipher = crypto.createCipheriv(alg, key, iv); cipher.setAAD(Buffer.from("aad", 'u

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

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/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

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

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

Pycrypto AES GCM encryption and Java decryption

Alastair McCormack I am using Pycryptodome (PyCrypto fork) to create AES-GCM ciphertext. I use the following Python code for encryption: cek = os.urandom(16) nonce = os.urandom(12) cipher = AES.new(cek, AES.MODE_GCM, nonce=nonce, mac_len=16) ciphertext = ciph

Pycrypto AES GCM encryption and Java decryption

Alastair McCormack I am using Pycryptodome (PyCrypto fork) to create AES-GCM ciphertext. I use the following Python code for encryption: cek = os.urandom(16) nonce = os.urandom(12) cipher = AES.new(cek, AES.MODE_GCM, nonce=nonce, mac_len=16) ciphertext = ciph

File encryption and decryption using AES

Rekha Ahir public long copyStreamsLong(InputStream in, OutputStream out, long sizeLimit) throws IOException { long byteCount = 0; IOException error = null; long totalBytesRead = 0; try { String key = "C4F9EA21977047