I'm using javax.crypto to do some cryptographic operations in my application. I use AES for encryption/decryption like this:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] cipherText = cipher.doFinal(plaintext);
byte[] iv = cipher.getIV(); //The problematic IV
The generated IV is prepended to the ciphertext after the enncryption.
The Java specification clearly says that the IV must be generated automatically if its is not provided to cipher.init():
If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values)
But sometimes I end up with ciphertexts that don't seem very random, such as this one (in base64):
AAAAAAAAAAAAAAAAAAAAAOmI9Qh1fMiG6HV3tKZK3q5sCruaPdYqYnoUOM00rs6YZY3EvecYfR6vTHzZqk7ugknR9ZMipedYWJB1YOLmSYg=
The bunch of A characters at the front is the IV. The IV is actually 16 zero-bytes.
Most of the time, the library generates proper, random IVs, but sometimes, it just pops out zeros. Why is this happening?
Some (most?) providers simply use a zero-byte filled IV as their default. My emphasis of your quote:
If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values)
When you look to the front of your ciphertext, you see that it starts with a bunch of "A" characters. It's Base 64 for 0x00 bytes.
If you want to make sure that you have a random IV, you have to generate it yourself:
SecureRandom r = new SecureRandom();
byte[] ivBytes = new byte[16];
r.nextBytes(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
The IV is not secure. It is prepended to the cyphertext, so any attacker only has to read the cyphertext and look at the first 16 bytes to see what it is.
It is not a good idea to always use the same IV -- it effectively turns the first block of your actual cyphertext into ECB mode, which is insecure.
I recommend generating your own random IV. You do not need to use a cryptographically secure RNG, since an attacker can see it anyway. You just need to avoid using the same IV for different messages. Even something simple like 8 bytes of random with an 8 byte (64 bit) counter will be enough to avoid the ECB effect. Change the key before the counter rolls over, and reset the counter to 0 when you change the key.
Related
I'm trying to do audio steganography. Before hiding data inside audio I encrypt the data with aes and then I embed bits at lsb in sequential bytes. The recovery and aes decryption works fine.
But if I try random bits for lsb it gives me the following error:
-->Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
the error points to
public byte[] decr**strong text**yptText(byte[] byteCipherText,Key secKey) throws Exception {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
See PKCS padding, note that PKCS#5 is a misnomer for PKCS#7 WRT AES because the AES implementation developers were to lazy to include the correct option name.
Because PKCS#7 padding has format requirements and there few byte sequences (~ 1^16 + 2^16 + ... + 15^16) that form correct padding out of 256^16 possible byte sequences the chance that random bytes would form valid PKCS#7 padding is very small.
You might be better off using CTR mode which does not require padding, just a unique key/counter pair for each encryption.
I want to encrypt a String to interger with fix lenght, How can I do that in Java.
tring to implement AES Algorithm but the out is a special Character and not a number.
String text = "Test TEST";
String key = "deadbeefbeefdead"; // 128 bit key
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher..doFinal(text.getBytes());
System.err.println(new String(encrypted));
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.err.println(decrypted
);
The question is not clear but here is some information:
Encryption generates a sequence of 8-bit bytes, not characters, not all 8-bit bytes are printable characters or even characters in most encodings. Generally if you require a printable string the encrypted data is Base64 or hex encoded. Each encrypted byte can be considered a uint8_t "integer".
AES is a block cipher, it takes 16-byte chunks and outputs 16-byte chunks. If the input is not a multiple of the block size padding (extra bytes) must be added to the input prior to encryption. "Bhaumik Patel" is 13 bytes so 3 bytes must be added prior to encryption and removed after decryption. Most block encryption libraries include a padding option, generally PKCS#7 (PKCS#5) but occasionally null padding.
There is also a mode,most commonally ECB (not secure) and CBC. In the case of CBC there is also a block-sized iv (initialization vector), generally a random sequence of bytes.
Unfortunately, encryption alone is generally only part of a secure solution.
Edit: The question text input was changed from "Bhaumik Patel" to ""Test TEST"".
I am currently using AES/CBC/PKCS5Padding for encrypting files in Java with 256 bytes key size, but while searching I found on stackexchange PKCS#5-PKCS#7 Padding and it is mentioned,
PKCS#5 padding is a subset of PKCS#7 padding for 8 byte block sizes
So I want to know
Will the performance of AES/CBC/PKCS7Padding will be better then AES/CBC/PKCS5Padding for the above configuration?
How can we configure the block size in Java as it is mentioned
PKCS#7 padding would work for any block size from 1 to 255 bytes.
My sample code is,
SecureRandom rnd = new SecureRandom();
IvParameterSpec iv = new IvParameterSpec(rnd.generateSeed(16));
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256);
SecretKey k = generator.generateKey();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
The block size is a property of the used cipher algorithm. For AES it is always 16 bytes.
So strictly speaking, PKCS5Padding cannot be used with AES since it is defined only for a block size of 8 bytes. I assume, AES/CBC/PKCS5Padding is interpreted as AES/CBC/PKCS7Padding internally.
The only difference between these padding schemes is that PKCS7Padding has the block size as a parameter, while for PKCS5Padding it is fixed at 8 bytes. When the Block size is 8 bytes they do exactly the same.
There were many questions about AES, but I have the following problem.
I'm currently using the following AES implementation to encrypt data
byte [] PRFkey = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
byte [] plaintext = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
SecretKeySpec encryptionKey=new SecretKeySpec(PRFkey, "AES");
Cipher cipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
byte[] encryptedData=cipher.doFinal(plaintext);
And it turned out that result is 32-bytes (256 bits). So I'm using AES-256. This implementation is to slow for me. How can I switch to AES-128? I don't need any padding or mode of operation or key hashing.
Thank you in advance.
You are already using 128-bit AES. This is determined by the length of the key you pass to Cipher.init(), which is sixteen bytes (128 bits) in your example.
The size of your output will depend upon your padding mode (and the size of the input data). Since you neglected to specify an operation mode or padding, your JCE provider has likely defaulted to "AES/ECB/PKCS5Padding". PKCS #5 padding will always add one additional block to the size of your output, hence you received 32 bytes of output and not 16 bytes.
Never allow your provider to select default values for you. Instead, specify the mode and padding explicitly:
Cipher cipher=Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
byte[] encryptedData=cipher.doFinal(plaintext); // will be 16 bytes
Just remember that if you specify no padding, your input data must always be an exact multiple of 16 bytes. Also note that ECB-mode has the property that identical plaintext values will produce identical ciphertext values. This is rarely desirable in a cryptographic system.
A similar question was asked on stack overflow here and will help provide you with the info you are looking for. An important point is that The JCA Reference Guide says that:
(Creating a Cipher Object) If no mode or padding is specified, provider-specific default values for the mode and padding scheme are used. For example, the SunJCE provider uses ECB as the default mode, and PKCS5Padding as the default padding scheme for DES, DES-EDE and Blowfish ciphers. This means that in the case of the SunJCE provider: Cipher.getInstance("DES") and Cipher.getInstance("DES/ECB/PKCS5Padding") are equivalent statements.
Thus since you are only specifying "AES" as the transformation, the default cipher for AES for Oracle JDK 7 is "AES/ECB/PKCS5Padding", link.
Additionally, the Cipher class defines the transformation "AES/ECB/NoPadding" that will get you a non-padded 16 byte value for your encryptedData. ECB is the default mode for AES, you could also choose "AES/CBC/NoPadding".
I'm trying to implement AES in Java and this is the code I use:
byte[] sessionKey = {00000000000000000000000000000000};
byte[] iv = {00000000000000000000000000000000};
byte[] plaintext = "6a84867cd77e12ad07ea1be895c53fa3".getBytes();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(iv));
byte[] ciphertext = cipher.doFinal(plaintext);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(iv));
byte[] deciphertext = cipher.doFinal(ciphertext);
I need this fixed key and IV for test purpose but I get the following exception:
Exception in thread "main"
java.security.InvalidAlgorithmParameterException:
Wrong IV length: must be 16 bytes long at
com.sun.crypto.provider.SunJCE_h.a(DashoA12275) at
com.sun.crypto.provider.AESCipher.engineInit(DashoA12275) at
javax.crypto.Cipher.a(DashoA12275) at
javax.crypto.Cipher.a(DashoA12275) at
javax.crypto.Cipher.init(DashoA12275) at
javax.crypto.Cipher.init(DashoA12275)
How can I use this fixed IV with this implementation of AES? Is there any way?
Firstly,
byte[] iv = {00000000000000000000000000000000};
creates a byte array of size 1 and not a byte array of size 32 (if that is your intention).
Secondly, the IV size of AES should be 16 bytes or 128 bits (which is the block size of AES-128). If you use AES-256, the IV size should be 128 bits large, as the AES standard allows for 128 bit block sizes only. The original Rijndael algorithm allowed for other block sizes including the 256 bit long block size.
Thirdly, if you are intending to use a AES-256, this does not come out of the box. You need to download and install the JCE Unlimited Strength Jurisdiction Policy Files (scroll to the bottom of the page); I would also recommend reading the accompanying license.
This would result in the following change to your code:
byte[] iv = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Finally, the initialization vector is meant to be unique and unpredictable. A sequence of 16 bytes, with each byte represented by a value of 0, is not a suitable candidate for an IV. If this is production code, consider getting help.
From Advanced Encryption Standard:
The standard comprises three block ciphers, AES-128, AES-192 and AES-256, adopted from a larger collection originally published as Rijndael. Each of these ciphers has a 128-bit block size, with key sizes of 128, 192 and 256 bits, respectively
(Emphasis added)
From Initialization Vector:
For block cipher modes of operation, the IV is usually as large as the block size of the cipher
Combine those two factors together, and you get that the IV is always 128 bits for AES, independent of the key size.
AES here is probably AES-128 not AES-256.You must include extra jar if you want to enable AES-256 as there are export control policies in place. So check that first. AES-128 is enough in most cases.
Your IV can't be more than 128 bits i.e. 16 bytes when it is AES-128. So change the initialization vector length.
That must work. Also, read this http://en.wikipedia.org/wiki/Initialization_vector
Warning: It is not a good practice to have a fixed IV. It must be random or pseudorandom to offer better security.
Why not just use something like that instead of using "magic numbers":
SecureRandom random = new SecureRandom();
byte[] iv = random.generateSeed(16);
So you get 16 random bytes for your iv.
The reason why I had this problem was because I was reading the IV as a String, and converting it to a byte array the wrong way.
Right way:
Hex.decodeHex(initializationVector.toCharArray()
using org.apache.commons.codec.binary.Hex
Wrong way:
initializationVector.getBytes()
The reason this was wrong, is because when you call getBytes(), it just takes all bits that represent the string and cuts them into bytes. So 0 ends up being written as the bits that make up the index of 0 in the Unicode table, which is not 0 but 30, and which would be written on 2 bytes.
Conversely, what you want here is actually that 0 be represented as the byte 00000000.
Not related to this but faced same issue.
IvParameterSpec ivParameterSpec = new IvParameterSpec(key1.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key2.getBytes("UTF-8"),"AES");
The mistake I made was key1 and key2 were Strings of length greater than 16. Changing their length to 16 fixed it.