Java AES-128 encryption of 1 block (16 byte) returns 2 blocks(32 byte) as output -
i'm using following code aes-128 encryption encode single block of 16 byte length of encoded value gives 2 blocks of 32 byte. missing something?
plainenc = aes.encrypt("thisisapassword!");
import java.security.*; import java.security.spec.invalidkeyspecexception; import javax.crypto.*; import sun.misc.*; public class aes { private static final string algo = "aes"; private static final byte[] keyvalue = new byte[] { 't', 'h', 'e', 'b', 'e', 's', 't', 's', 'e', 'c', 'r','e', 't', 'k', 'e', 'y' }; public static string encrypt(string data) throws exception { system.out.println("string length: " + (data.getbytes()).length); //length = 16 key key = generatekey(); cipher chiper = cipher.getinstance(algo); chiper.init(cipher.encrypt_mode, key); byte[] encval = chiper.dofinal(data.getbytes()); system.out.println("output length: " + encval.length); //length = 32 string encryptedvalue = new base64encoder().encode(encval); return encryptedvalue; } public static string decrypt(string encrypteddata) throws exception { key key = generatekey(); cipher chiper = cipher.getinstance(algo); chiper.init(cipher.decrypt_mode, key); byte[] decordedvalue = new base64decoder().decodebuffer(encrypteddata); byte[] decvalue = chiper.dofinal(decordedvalue); string decryptedvalue = new string(decvalue); return decryptedvalue; } private static key generatekey() throws exception { key key = new secretkeyspec(keyvalue, algo); return key; } }
cipher.getinstance("aes")
returns cipher uses pkcs #5 padding. padding added in cases – when plaintext multiple of block size, whole block of padding added.
specify intentions explicitly in cipher.getinstance()
call avoid relying on defaults , potentially causing confusion:
cipher.getinstance("aes/ecb/nopadding");
you see using ecb mode, bad choice in situation.
Comments
Post a Comment