Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

AES/ECB/NoPadding

658018Jul 21 2011 — edited Jul 22 2011
Dear ALL,

I am having a problem AES algorithm

I'm using AES/ECB/NoPadding
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.jpos.iso.ISOUtil;

public class AesTest {

	static Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
	public static void main(String[] args) {
		
		Security.addProvider(p);
		try {

			byte aesKeyByte[] =  ISOUtil.hex2byte("EE5C261E5B0FF0E78CFF3D6D65DDB220");
			
			byte clearValue[] =  ISOUtil.hex2byte("7C096716F12BAE6B");

			SecretKey AESKey = new SecretKeySpec(aesKeyByte,"AES");
			
			byte enout[] = encrypt(AESKey, clearValue, p, "ECB", null);
			
			System.out.println("ENCR DATA : "+ISOUtil.hexString(enout));
			
			byte deout[] = decrypt(AESKey, enout, p, "ECB", null);
			
			System.out.println("DER DATA : "+ISOUtil.hexString(deout));
			
		
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}
	
	
	public static byte[] encrypt(SecretKey secretKey, byte[] clearBytes, Provider p,
			String mode, byte[] IV) throws Exception {

		if ("CBC".equals(mode)) {
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", p
					.getName());
			cipher
					.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(
							IV));
			return cipher.doFinal(clearBytes);
		} else {
			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", p
					.getName());
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			return cipher.doFinal(clearBytes);
		}

	}

	
	public static byte[] decrypt(SecretKey secretKey, byte[] ciperBytes, Provider p,
			String mode, byte[] IV) throws Exception {

		if ("CBC".equals(mode)) {
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", p
					.getName());
			cipher
					.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(
							IV));
			return cipher.doFinal(ciperBytes);
		} else {
			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", p
					.getName());
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			return cipher.doFinal(ciperBytes);
		}

	}

}
Error

javax.crypto.IllegalBlockSizeException: data not block size aligned
at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at AesTest.encrypt(AesTest.java:72)
at AesTest.main(AesTest.java:41)


Regards

Edited by: EJP on 21/07/2011 15:45
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 19 2011
Added on Jul 21 2011
6 comments
4,933 views