Milad Barai
Milad Barai

Reputation: 11

AES encryption and decryption data loss

When i try to encrypt a MD5 hash of a key using AES ECB, And afterwards decrypt it i get diffrent results:

Before: >•ly†lrœËGQ2¶ª€

After: 0¦t‹ d)§¥›B?W

The code i use for Encryption and Decryption is:

public class AES {
    private String a= "AES/ECB/NoPadding";
    private byte[] key;
    Cipher c;
    public AES(byte [] key) throws NoSuchAlgorithmException, NoSuchPaddingException{
            this.key = key;
            c = Cipher.getInstance(a);
        }
public String encrypt(byte[] Data) throws Exception{
        Key k = new SecretKeySpec(key, "AES");
        c.init(Cipher.ENCRYPT_MODE, k);
        byte[] encoded = c.doFinal(Data);
        String encrypted= new String(encoded);
        return encrypted;

    }
public String decrypt(byte[] v) throws Exception{
        Key k = new SecretKeySpec(key, "AES");
        if(v.length%16!=0)
            return null;
        c.init(Cipher.DECRYPT_MODE, k);
        byte[] decv = c.doFinal(v);
        String decrypted = new String(decv);
        return decrypted;
    }
}

Upvotes: 0

Views: 611

Answers (1)

erickson
erickson

Reputation: 269847

This doesn't work:

String encrypted= new String(encoded);

The cipher text bytes in encoded are pseudo-random gibberish. It's highly unlikely they form a valid text encoding, regardless of your platform default.

If you need a text representation, use base-64 encoding:

String encrypted = Base64.getEncoder().encodeToString(encoded);

This is a common mistake, although it manifests in different ways, so the "questions" are varied and hard to identify as duplicates. Here's another answer with more detail.

Upvotes: 1

Related Questions