I am actually Researching the difference between the ECB mode of AES encryption and CBC Mode. After some study I came to know that ECB mode has some flaws at it creates same ciphertext for the plaintext if encrypted with the same key and same content. on the other hand, in CBC there is Initialization Vector to overcome this issue which creates randomness of bytes on run-time for each encryption.
Now, on few forums I came to know that if there are similar blocks between two plain texts, then it will produce the same ciphertext each time; which will help the hacker to identify the common pattern of cipher.
I tried it with some Java code and provided two 2 plain texts as below:
Jimmy Anderson.
Corrie Anderson.
Now the word Anderson is common between both but when i encrypted it and printed the output, it produced different ciphertexts. However, encrypting the same piece of plain text produced similar ciphertexts that's fine though. But why it produced different ciphers for common last names?
another question is that, if we are using the random key generation on each encryption cycle, then It will always produce a different cipher for even same plain text because the key is different?
Then whats the need of CBC if it is catered here?
Can someone help me out in this?
Any help will be appreciated :).
public static String encryptwithecb ( byte[] plaintext, SecretKey key ) throws Exception
{
Cipher cipher = Cipher.getInstance( "AES/ECB/PKCS5Padding" );
SecretKeySpec keyspec = new SecretKeySpec( key.getEncoded(), "AES" );
cipher.init( Cipher.ENCRYPT_MODE, keyspec );
byte[] cipherText = cipher.doFinal( plaintext );
return Base64.getEncoder().encodeToString( cipherText );
}
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
// Generate Key
SecretKey key = keyGenerator.generateKey();
System.out.println("");
System.out.println("");
System.out.println("***** ENCRYPT WITH ECB ****** ");
System.out.println("");
String name1 = "Jimmy Anderson";
String name2 = "Corrie Anderson..";
String ecb = encryptwithecb( name1.getBytes("UTF-8") , key);
String ecb2 = encryptwithecb( name2.getBytes("UTF-8") , key);
String ecb3 = encryptwithecb( name1.getBytes("UTF-8") , key);
System.out.println(ecb);
System.out.println(ecb2);
System.out.println(ecb3);
System.out.println("");
System.out.println("***** ENCRYPT WITH ECB ****** ");
System.out.println("");
System.out.println("");
Output
***** ENCRYPT WITH ECB ******
gs3y1N8jA7kwzO/c/dzwEA==
yKFC43ySA1NBAnRdvp9jEHtfcJeM7bAlmcMY63Aeupc=
gs3y1N8jA7kwzO/c/dzwEA==
***** ENCRYPT WITH ECB ******