java


ECB and CBC AES output is equal in Java


I've played around with the Java AES En/Decryption and used different cyper modes for this. Namely I use CBC and ECB. As ECB is considered to be weak, I wanted to go with CBC.
I assumed the output of the encrypted texts ob cbc and ecb are different, but they are equal. How is this possible?
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import com.instana.backend.common.exception.InstanaException;
public class AESTest {
private static String pwd = "etjrgp9user9fu3984h1&(/&%$§";
public static void main(String[] args) throws Exception {
System.out.println("UNSECURE WITH ECB:");
String ecbEncrypt = encrypt("YOLO", cypher(Cipher.ENCRYPT_MODE, "AES"));
System.out.println("Encrypted: " + ecbEncrypt);
String ebcDecrypt = decrypt(ecbEncrypt, cypher(Cipher.DECRYPT_MODE, "AES"));
System.out.println("Decrypted: " + ebcDecrypt);
System.out.println("=====================================");
System.out.println("SECURE WITH CBC");
String cbcEncrypt = encrypt("YOLO", cypher(Cipher.ENCRYPT_MODE, "AES/CBC/PKCS5Padding"));
System.out.println("Encrypted: " + cbcEncrypt);
String cbcDecrypt = decrypt(cbcEncrypt, cypher(Cipher.DECRYPT_MODE, "AES/CBC/PKCS5Padding"));
System.out.println("Decrypted: " + cbcDecrypt);
System.out.println("=====================================");
System.out.println("Decrypting CBC with ECB");
}
public static String encrypt(String superDuperSecret, Cipher cipher) throws IOException {
try {
byte[] encrypted = cipher.doFinal(superDuperSecret.getBytes("UTF-8"));
return new String(new Hex().encode(encrypted));
} catch (Exception e) {
throw new InstanaException("Encryption of token failed.", e);
}
}
public static String decrypt(String superDuperSecret, Cipher cipher) {
try {
byte[] encrypted1 = new Hex().decode(superDuperSecret.getBytes("UTF-8"));
return new String(cipher.doFinal(encrypted1));
} catch (Exception e) {
throw new InstanaException("Encrypted text could not be decrypted.", e);
}
}
private static Cipher cypher(int mode, String method)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException,
InvalidAlgorithmParameterException {
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(pwd.toCharArray(), pwd.getBytes(), 128, 128);
SecretKey tmp = skf.generateSecret(spec);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance(method);
if(method.contains("CBC")) {
byte[] ivByte = new byte[cipher.getBlockSize()];
IvParameterSpec ivParamsSpec = new IvParameterSpec(ivByte);
cipher.init(mode, key, ivParamsSpec);
}else{
cipher.init(mode, key);
}
return cipher;
}
}
Since you're passing an empty IV (you never put anything inside your ivByte), the operations performed for the first block are identical regardless of the mode being used. Encrypting a longer payload would result in the second block being chained to the first block in the case of CBC and the following blocks would be different between ECB/CBC.
You should pass a non-empty IV when using CBC mode, so the first block will be xorred with the IV, resulting in different encrypted values starting from the first block.

Related Links

How to use TLS 1.2 in Java 6
libGDX makes screen smaller [Ubuntu]
Angular Working with object: Fix it
URL encoding of “&”
Camel JDBC Route - CamelJdbcRowCount missing
ReeantrantLock and Condition variable
How to Display Help In Wizard's Tray
Retrieve view in OnClickListener
How do I let a user interrupt an endless loop in Java?
Cannot take picture or choose image from gallery
How do you use PrintJobInfo.Builder where I can setCopies in android.print?
remove termination symbol from xml
Putting unique random number in array
Android SQL database organization [closed]
How to resolv: java.sql.SQLException: setDate, Exception = Invalid year value
My app is force closing when clicking on button to switch to another activity. here i am putting my code

Categories

HOME
sendgrid
pdf
hive
blogger
openstack
deezer
pycharm
path-finding
smarty
json.net
iot
survey
ebean
enterprise-library-5
bs4
handsontable
mapserver
windows-azure-storage
django-simple-history
reactcsstransitiongroup
pythonanywhere
oracle-coherence
samoa
java-3d
hammerspoon
blazemeter
java-7
centos6.5
pingfederate
bootstrap-material-design
saas
webkitspeechrecognition
r-raster
socialengine
code-contracts
stringtemplate
lxd
rotational-matrices
wixsharp
occlusion
dism
botbuilder
nxlog
heightmap
convertapi
auto-update
osx-mavericks
network-flow
filepicker
upstart
logparser
worksheet
sage-one
domain-model
topbeat
jquery-filter
wdf
google-feed-api
log4c
ctest
angstrom-linux
livequery
nessus
revolution-r
ford-fulkerson
hsv
qdialog
ionic
service-accounts
formatjs
xc16
socketexception
phpthumb
comexception
mbr
terminal-services
commoncrypto
tidy
apc
xamlparseexception
plasma
ember-app-kit
eventlistener
simba
coderush
parametric-equations
uiviewanimation-curve
zpt
gcj
coredump
propagation
photoshop-cs4
defensive-programming
windows-live-messenger

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App