0

I have some data that was encrypted with AES in Java. I would now like to decrypt in Python. For reference here is the decrypt Java code:

public static String decryptAES(String input, String key)  throws EncryptionException {

    String clearText = null;
    byte[] keyBytes = key.getBytes();
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(1, keySpec);
        // We need to revert our plus sign replacements from above
        input = input.replaceAll(Pattern.quote("_"), "+");
        byte[] decodedInput = Base64.decodeBase64(input.getBytes());
        byte[] clearTextBytes = cipher.doFinal(decodedInput);
        clearText = new String(clearTextBytes);
        clearText = StringUtils.strip(clearText, "{");
    } catch (Exception ex) {
        throw new EncryptionException(ex);
    } 

    return clearText;

}

Here is what I have

from Crypto.Cipher import AES

encryptionKey = "]zOW=Rf*4*5F^R+?frd)G3#J%tH#qt_#"
encryptedData = "Hx8mA8afdgsngdfCgfdg1PHZsdfhIshfgdesd4rfgdk="

cipher = AES.new(encryptionKey.encode(), AES.MODE_ECB)

plain = cipher.decrypt(encryptedData.encode())

print(plain)

But I am getting a "ValueError: Data must be aligned to block boundary in ECB mode" I did google and did find some suggestions like ValueError: Data must be aligned to block boundary in ECB mode but I couldn't really get it to work. No idea what the block size should be

khelwood
  • 55,782
  • 14
  • 81
  • 108
klind
  • 855
  • 2
  • 21
  • 33
  • Just so I can play with this, what unencrypted value do you expect? – JonSG Apr 30 '21 at 21:11
  • no base64decoding on Python? – kelalaka Apr 30 '21 at 21:14
  • `cipher.init(1, keySpec)` initializes `cipher` for **en**cryption and not **de**cryption, since `1` corresponds to `Cipher.ENCRYPT_MODE`. Better apply the predefined constants so that something like this doesn't happen, i.e. for decryption `Cipher.DECRYPT_MODE`. However, even with this change, your data won't provide a UTF8 decodable plaintext (if such should result). – Topaco May 01 '21 at 07:41

1 Answers1

1

Decoding with Base64 as suggested by @kelalaka solves the problem of Value error, but the output seems to be just random bytes:

import base64

from Crypto.Cipher import AES

encryptionKey = "]zOW=Rf*4*5F^R+?frd)G3#J%tH#qt_#"
encryptedData = "Hx8mA8afdgsngdfCgfdg1PHZsdfhIshfgdesd4rfgdk="

data = base64.b64decode(encryptedData)

cipher = AES.new(encryptionKey.encode(), AES.MODE_ECB)

plain = cipher.decrypt(data)

print(plain)

Output: b'\xcfh(\xb5\xec%(*^\xd4\xd3:\xde\xfb\xd9R<B\x8a\xb2+=\xbf\xc2%\xb0\x14h\x10\x14\xd3\xbb'

PGR
  • 116
  • 6