Samuel
Samuel

Reputation: 1

AES Decryption in Java Not Returning the Same String as the Plaintext

I am trying to create a program in java in which part of it uses AES encryption to encrypt data for my final project in a coding class. Here is the code that I am using for my encryption:

static String symmetric(String info, String key, String mode) {
    try {
        Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte [] bytes = Base64.getDecoder().decode(Crypto.sha256(key));
        byte [] information = Base64.getDecoder().decode(info);
        Key k = new SecretKeySpec(bytes, "AES");

        if (mode.equals("ENCRYPT")) {
            c.init(Cipher.ENCRYPT_MODE, k);
        } else if (mode.equals("DECRYPT")) {
            c.init(Cipher.DECRYPT_MODE, k);
        }
            
        return (Base64.getEncoder().encodeToString(c.doFinal(information)).trim());
        
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
    return (null);
}

When I encrypt my data using String ciphterText = symmetric("message", "key", "ENCRYPT") and decrypt the ciphertext using symmetric(cipherText, "key", "DECRYPT"), the string it returns is "messagc=". I'm worried that the padding is weird but I don't know how to fix it.

FYI: Crypto.sha256(String input) is a method I created that returns the sha256 hash of info as a base 64 string. Here is the code for it if it helps:

public static String sha256(String input) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte [] tempHash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

        return (Base64.getEncoder().encodeToString(tempHash));

    } catch (NoSuchAlgorithmException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }

    return (null);
}

Also I know ECB is not secure compared to other methods that use initialization vectors, but it is a small project and I don't have enough time to do that, which is the same reason why I'm not salting my hashes. Is there anything I can do to fix it?

Upvotes: 0

Views: 323

Answers (1)

erickson
erickson

Reputation: 269627

This is a problem with the way you are using base-64 encoding.

When you encrypt, you are treating "message" as base-64 encoded bytes. The last block is "age". A strict decoder would reject that input, because it is missing padding, and has some extra bits that spill over into the third byte. But a permissive decoder ignores that, and decodes the array as { 0x99, 0xeb, 0x2c, 0x6a, 0x07 }

The correct base-64 encoding of { 0x99, 0xeb, 0x2c, 0x6a, 0x07 } is "messagc=".

To make this work correctly, every statement in your method should differ depending on the mode flag. It would be more clear and clean to separate encrypt and decrypt methods.

Upvotes: 1

Related Questions