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.
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 am using the following code in my android application to encrypt a string in Triple DES using the Encrypted Code Book (ECB) mode with three independent keys (aka 3DESede), which are provided as a 24 byte sized key array. Therefore I use the Java Crypto API. This works pretty well, but if I encrypt an eight character string I get a 16 byte cipher text, which should not happen as 3DES operates on chunks of 64 bit (resp. 8 byte). Same holds for the PKCS5 padding as this also operates on chunks of 64 bit. So my question is what causes this problem?
private static byte[] encryptText(String plaintext, byte[] keyBytes) throws Exception {
// Get plaintext as ASCII byte array
final byte[] plainBytes;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
plainBytes = plaintext.getBytes(StandardCharsets.US_ASCII);
} else {
plainBytes = plaintext.getBytes("US-ASCII");
}
// Generate triple DES key from byte array
final DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey key = keyFactory.generateSecret(keySpec);
// Setup the cipher
final Cipher c3des = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c3des.init(Cipher.ENCRYPT_MODE, key);
// Return ciphertext
return c3des.doFinal(plainBytes);
}
PKCS5Padding adds 1-8 bytes of padding when used with DES. If you encrypt 8 bytes you will get 8 additional bytes of padding to get to an even number of blocks.
If you used Cipher.getInstance("DES/ECB/NoPadding") and encrypted 8 bytes, you will get 8 bytes of cipher text.
When PKCS#5 padding is used it must always add padding otherwise on decryption there would be no way to determine if padding was added. So, even if the input data is an exact multiple of the block size padding must be added and that will be 8 bytes.
See PKCS padding:
If the original data is an integer multiple of N bytes, then an extra block of bytes with value N is added. This is necessary so the deciphering algorithm can determine with certainty whether the last byte of the last block is a pad byte indicating the number of padding bytes added or part of the plaintext message. Consider a plaintext message that is an integer multiple of N bytes with the last byte of plaintext being 01. With no additional information, the deciphering algorithm will not be able to determine whether the last byte is a plaintext byte or a pad byte. However, by adding N bytes each of value N after the 01 plaintext byte, the deciphering algorithm can always treat the last byte as a pad byte and strip the appropriate number of pad bytes off the end of the ciphertext; said number of bytes to be stripped based on the value of the last byte.
PKCS#5 padding is identical to PKCS#7 padding, except that it has only been defined for block ciphers that use a 64-bit (8 byte) block size. In practice the two can be used interchangeably.
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.
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.
I implement this via java , BouncyCastle Provider
use Block mode = ECB and Padding mode = PKCS7Padding
I noticte that if i encrypt data that has 32 byte length(such as 61626162616261626162616261626162 which is hex value of abababababababab) i get 64 bytes length cipher text(f21ee0564ebd5274e10bf4590594b1e16a19592b917b19ee106f71d41d165289) is this cipher text valid? from what i read it look like if you encrypt less than 32 byte length data the algorithm will padding it to 32 byte length and produce a 32 byte length cipher text but if you put in exactly 32 byte length data shouldn't you receive the 32 byte length cipher text ,also if i put in data with more length than 32 byte it will padded to 64 byte cipher text correctly
this is what my code look like :
public static byte[] encrypt(byte[] plainText, byte[] keyBytes)
throws GeneralSecurityException {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(plainText);
return cipherText;
}
thx for your reply
You are confusing hexadecimal characters and bytes. Two hexadecimal characters can be used to represent a single byte. So your input is likely 16 bytes and your output then becomes 32 bytes. AES is a 128 bits = 16-byte block cipher.
PKCS#7 padding is defined to pad 16 byte block ciphers. To make sure that the last byte of the plain text is not mistaken for padding, PKCS#7 padding always pads. This means that in the unfortunate circumstance that the plain text is dividable by 16, it will add an entire block of padding. The padding consists of a string of bytes indicating the length of the string in each byte, so for your case the padding consists of the following bytes, represented by hexadecimals: 10101010101010101010101010101010.
Note that the default provider of Java uses "PKCS5Padding" instead of "PKCS7Padding". Both are identical, although PKCS#5 padding officially is only for 64 bit = 8 byte block ciphers. Bouncy Castle will accept that string as well, so it is better to specify "PKCS5Padding" for the sake of compatibility.
There is no padding specified for AES that would use 32 bytes as it is only a 16 byte block cipher. It would make sense for Rijndael-256 which is a 32 byte block cipher, but that algorithm hasn't been standardized by NIST and should therefore be avoided.
The PKCS7 padding is explained here:
http://en.wikipedia.org/wiki/Padding_(cryptography)#Byte_padding
It adds between 1 and blockLength bytes, all of which are equal to the size of the padding. This means your message will be padded by 16 16's, creating a 32-byte message that gets subsequently encoded with AES.
Note that your message is 16 bytes, not 32.
In general, a padding of zero length is never used, because it cannot be distinguished from non-zero padding (and the padding must be done in a reversible fashion).