Skip to content

Instantly share code, notes, and snippets.

@KushtrimPacaj
Last active May 31, 2024 01:21
Show Gist options
  • Save KushtrimPacaj/43a383ab419fc222f80e to your computer and use it in GitHub Desktop.
Save KushtrimPacaj/43a383ab419fc222f80e to your computer and use it in GitHub Desktop.
AES encryption in Java, equivalent of Crypt ( Encrypter.php class ) on Laravel (PHP)
import android.util.Base64;
import android.util.Log;
import com.google.gson.Gson;
import org.apache.commons.codec.binary.Hex;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesEncryptDecrypt
{
public static String encrypt(byte[] keyValue, String plaintext) throws Exception {
Key key = new SecretKeySpec(keyValue, "AES");
//serialize
String serializedPlaintext = "s:" + plaintext.getBytes().length + ":\"" + plaintext + "\";";
byte[] plaintextBytes = serializedPlaintext.getBytes("UTF-8");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key);
byte[] iv = c.getIV();
byte[] encVal = c.doFinal(plaintextBytes);
String encryptedData = Base64.encodeToString(encVal, Base64.NO_WRAP);
SecretKeySpec macKey = new SecretKeySpec(keyValue, "HmacSHA256");
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
hmacSha256.init(macKey);
hmacSha256.update(Base64.encode(iv, Base64.NO_WRAP));
byte[] calcMac = hmacSha256.doFinal(encryptedData.getBytes("UTF-8"));
String mac = new String(Hex.encodeHex(calcMac));
//Log.d("MAC",mac);
AesEncryptionData aesData = new AesEncryptionData(
Base64.encodeToString(iv, Base64.NO_WRAP),
encryptedData,
mac);
String aesDataJson = new Gson().toJson(aesData);
return Base64.encodeToString(aesDataJson.getBytes("UTF-8"), Base64.DEFAULT);
}
public static String decrypt(byte[] keyValue, String ivValue, String encryptedData, String macValue) throws Exception {
Key key = new SecretKeySpec(keyValue, "AES");
byte[] iv = Base64.decode(ivValue.getBytes("UTF-8"), Base64.DEFAULT);
byte[] decodedValue = Base64.decode(encryptedData.getBytes("UTF-8"), Base64.DEFAULT);
SecretKeySpec macKey = new SecretKeySpec(keyValue, "HmacSHA256");
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
hmacSha256.init(macKey);
hmacSha256.update(ivValue.getBytes("UTF-8"));
byte[] calcMac = hmacSha256.doFinal(encryptedData.getBytes("UTF-8"));
byte[] mac = Hex.decodeHex(macValue.toCharArray());
if (!Arrays.equals(calcMac, mac))
return "MAC mismatch";
Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding"); // or PKCS5Padding
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decValue = c.doFinal(decodedValue);
int firstQuoteIndex = 0;
while (decValue[firstQuoteIndex] != (byte) '"') firstQuoteIndex++;
return new String(Arrays.copyOfRange(decValue, firstQuoteIndex + 1, decValue.length - 2));
}
}
/**
* Created by Kushtrim on 06.10.2015.
*/
public class AesEncryptionData {
public String iv;
public String value;
public String mac;
public AesEncryptionData(String iv, String value, String mac) {
this.iv = iv;
this.value = value;
this.mac = mac;
}
}
@KushtrimPacaj
Copy link
Author

@nasznjoka
When you encrypt a text with Crypt in Laravel, you get a base64 string.
To decrypt,decode that base64, and you get a JSON object like the AesEncryptionData class above. Then proceed with the decrypt method.

@madita
Copy link

madita commented Nov 29, 2016

Could you please give an example in use? How to use the App_Key from Laravel in this class?
How can I decrypt a string from Laravle with this?

@rnofriwandikepoo308
Copy link

If I want to use decrypt with sample word in java and Println the result..
how do i know byte[] keyValue, String ivValue, String encryptedData, String macValue for method decrypt?

@rahmatwaisi
Copy link

@madita did you find a way to do that? please share.

@KushtrimPacaj
Copy link
Author

Hi @madita , @mr648 .
I checked the code from my old project. Here's a further example:

  public static String getDecryptedString(String encryptedString) {
        String aesDataString = new String(Base64.decode(encryptedString.getBytes(), Base64.DEFAULT));

        AesEncryptedData aesEncryptedData = new Gson().fromJson(aesDataString, AesEncryptedData.class);

        String decrypted = null;
        try {
            decrypted = decrypt(
                    SECRET_KEY.getBytes("UTF-8"),
                    aesEncryptedData.iv,
                    aesEncryptedData.value,
                    aesEncryptedData.mac
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decrypted;
    }

@vjivandro
Copy link

how to call method decrypt?

@VijaySankhat
Copy link

Do we need to pass IvParameterSpec in c.init(Cipher.ENCRYPT_MODE, key); as last parameter?

@kyawhtut-cu
Copy link

kyawhtut-cu commented Aug 27, 2021

Can get that for the jquery version or PHP version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment