AES 128 Compatibility between android and Objective C - java

I have two applications: Android and iOS (Objective-C). And I'm trying to implement and encryption system so I can encrypt on both apps and decrypt in a server application. The problem is that I'm using AES128-ECB but the base64 key that I'm getting from android does not match with my objective c key. I have no idea what I'm missing.
Here are the snippets:
IOS
- (NSData*) EncryptAES: (NSString *) key{
char keyPtr[kCCKeySizeAES128+1];
bzero( keyPtr, sizeof(keyPtr) );
[key getCString: keyPtr maxLength: sizeof(keyPtr) encoding:NSUTF8StringEncoding];
size_t numBytesEncrypted = 0;
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
const unsigned char iv[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
CCCryptorStatus result = CCCrypt( kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyPtr,
kCCKeySizeAES128,
iv,
[self bytes], [self length],
buffer, bufferSize,
&numBytesEncrypted );
if( result == kCCSuccess )
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
else {
NSLog(#"Failed AES");
}
return nil;
}
And then:
NSString *pass = #"WORD_TO_ENCRYPT";
NSString *key = #"STRING_KEY";
//Encryption - APPROACH 1
NSData *data = [pass dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [data EncryptAES:key];
NSString* encryptedBase64 = [self Base64Encode:encryptedData];
NSLog(#"%#", encryptedBase64);
This is my Java function:
String plainTextKey = "STRING_KEY";
String plainText = "WORD_TO_ENCRYPT";
// Encrypt where jo is input, and query is output and ENCRPYTION_KEy is key
//String inputtt = "some clear text data";
byte[] input = new byte[0];
String skyKey;
input = plainText.getBytes("utf-8");
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(plainTextKey.getBytes("UTF-8"));
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skc);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
String encode = Base64.encode(cipherText);
System.out.println(encode);
I'm banging my head against the wall without knowing what I'm missing.
Thanks in advance for your help!
PS: I don't have any particular reason to use AES128-ECB. I can use any other algorithm if the multi system compatibility is simpler.

On the Android side, when you initialize the Cipher instance, you must provide the matching IV.
byte[] iv = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
cipher.init(Cipher.ENCRYPT_MODE, skc, new IvParameterSpec(iv));

Avoid using an hardcoded IV for the encryption mechanism, at least on Android. The usage of Random Number Generators is advised, but if you can not provide a random value, at least build the IV from the key.
On the other hand, you won't have good security if everything is derived from the password; you need some randomness in every message.
Make sure to store the IV used during the encryption so you can properly apply it back on the decryption.
byte[] iv = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
cipher.init(Cipher.ENCRYPT_MODE, skc, new IvParameterSpec(iv));

Related

javax.crypto.BadPaddingException: Given final block not properly padded - Strange error

javax.crypto.BadPaddingException: Given final block not properly padded - This is the error which I've got. I do not know why. My code seems to be alright. The key is the same during encrypting and decrypting. What I can say is that none of the already answered questions contain solution for my problem. Here is my code:
public String decrypt(String text) throws Exception {
String key = "SiadajerSiadajer"; // 128 bit key
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
byte[]encrypted = text.getBytes();
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted)); //Here is the error
return decrypted;
}
And the encryption mechanism in php
function encrypt($data, $size)
{
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
function decrypt($data)
{
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
$key = "SiadajerSiadajer";
$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
$name = openssl_encrypt(encrypt($name, 16), 'AES-256-CBC', $key, 0, $iv);
EDIT
Now in the php part my code is:
$key = "SiadajerSiadajer";
$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
$EIV = base64_encode($iv);
$name = openssl_encrypt(encrypt($name, 16), 'AES-256-CBC', $key, 0, $EIV);
And it gives me warning:Warning: openssl_encrypt(): IV passed is 24 bytes long which is longer than the 16 expected by selected cipher, truncating in C:\xampp2\htdocs\standardfinalinserting.php on line 68
And in Java part my decryption method is exactly like in the answer for my question but after running it gives me an error: java.security.InvalidKeyException: Illegal key size on the line:
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
EDIT 2:
So this is my whole Main class. It contains your whole Java code example
public class Main {
private byte[] padKey(byte[] key) {
byte[] paddedKey = new byte[32];
System.arraycopy(key, 0, paddedKey, 0, key.length);
return paddedKey;
}
private byte[] unpad(byte[] data) {
byte[] unpaddedData = new byte[data.length - data[data.length - 1]];
System.arraycopy(data, 0, unpaddedData, 0, unpaddedData.length);
return unpaddedData;
}
public String decrypt(String encodedJoinedData) throws Exception {
// Base64-decode the joined data
byte[] joinedData = Base64.decode(encodedJoinedData);
// Get IV and encrypted data
byte[] iv = new byte[16];
System.arraycopy(joinedData, 0, iv, 0, iv.length);
byte[] encryptedData = new byte[joinedData.length - iv.length];
System.arraycopy(joinedData, iv.length, encryptedData, 0, encryptedData.length);
// Pad key
byte[] key = padKey("SiadajerSiadajer".getBytes());
Key aesKey = new SecretKeySpec(key, "AES");
// Specify CBC-mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec); //HERE IS THE ERROR
// Decrypt data
byte[] decryptedData = cipher.doFinal(encryptedData);
// Remove custom padding
byte[] unpaddedData = unpad(decryptedData);
return new String(unpaddedData);
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String encodedJoinedData = "RB6Au33KGOF1/z3BQKqievUmh81Y8q4uw7s4vEs9xurQmNZAKwmhRQtS9wGYKQj8cJaPpK2xaDzx3RppQ8PsM/rQ9/p0Lme+x75dozBEbmFn6Q9eCXOCiCivVsKzZ8Vz";
String decryptedData = new Main().decrypt(encodedJoinedData);
System.out.println(decryptedData + " - " + decryptedData.length());
}
}
Running the code results in error:
Exception in thread "main" java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
at javax.crypto.Cipher.implInit(Cipher.java:805)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1396)
at javax.crypto.Cipher.init(Cipher.java:1327)
at com.dd.escuel.Main.decrypt(Main.java:43)
at com.dd.escuel.Main.main(Main.java:57)
There are a few issues with the Java-code:
In the PHP-code AES-256 is used, thus, the key must have a length of 32 Byte. Shorter keys are automatically right padded with zeros. This happens in your PHP-code since your key SiadajerSiadajer has a length of only 16 Byte. The key-padding must also be done in the Java-code. For this, e.g. the following Java-method can be used:
private byte[] padKey(byte[] key) {
byte[] paddedKey = new byte[32];
System.arraycopy(key, 0, paddedKey, 0, key.length);
return paddedKey;
}
With Cipher.getInstance("AES") the ECB-mode and PKCS5Padding are chosen by default. The CBC-mode must be explicitly specified in the Java-code with
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
In the PHP-method openssl_encrypt the fourth parameter $options is set to 0 which means that the returned data are Base64-encoded. Thus, in the Java-code the data have to be Base64-decoded before decryption:
byte[]encryptedData = Base64.decode(text);
Since the CBC-mode is used the IV of the encryption must be considered. A possible approach is to Base64-encode the IV in the PHP-code (subsequent to the encryption) with
$encodedIV = base64_encode($iv);
and pass that value to the Java-method decrypt as second parameter. Here, the IV must be decoded and used for the decryption:
byte[] iv = Base64.decode(ivEncoded);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
...
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
In the PHP-method openssl_encrypt the fourth parameter $options is set to 0 which means that the default padding (PKCS7) is used. Moreover, in the PHP-method encrypt a kind of custom padding is implemented (btw: the name of the method is unsuitable since it doesn't encrypt) and thus, it's padded twice. Therefore, after the decryption the custom padding (which may consist of white spaces) must be removed in the Java-code:
byte[] unpaddedData = unpad(decryptedData);
with
private byte[] unpad(byte[] data) {
byte[] unpaddedData = new byte[data.length - data[data.length - 1]];
System.arraycopy(data, 0, unpaddedData, 0, unpaddedData.length);
return unpaddedData;
}
Altogether:
public String decrypt(String text, String ivEncoded) throws Exception {
// Pad key
byte[] key = padKey("SiadajerSiadajer".getBytes());
Key aesKey = new SecretKeySpec(key, "AES");
// Base64 decode data
byte[]encryptedData = Base64.decode(text);
// Base64 decode iv
byte[] iv = Base64.decode(ivEncoded);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
// Specify CBC-mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
// Decrypt
byte[] decryptedData = cipher.doFinal(encryptedData);
// Remove custom padding
byte[] unpaddedData = unpad(decryptedData);
return new String(unpaddedData);
}
Test:
PHP-code input: Plain text ($data), key ($key):
$data = 'This is a plain text which needs to be encrypted...';
$key = "SiadajerSiadajer";
PHP-code output: Base64 encoded IV ($encodedIV), encrypted data ($name):
$encodedIV = 'Dg+Zs3mqIJeDOOEPMT5F4Q==';
$name = '8dXjeQhx2WSswQOQXLcyMKNpa5s413yI2Ku8WiIB/xtA2pEjrKcl5kWtrOh9k4A12Jl0N/z6tH67Wybhp/OwTi1NtiJOZxl3w6YQufE29oU=';
If that output is used as input for the Java-method decrypt the decrypted data equals the plain text.
Concerning the PHP-code I would suggest to remove either the custom or the default (PKCS7) padding (if you have the choice). The latter can be achieved by using the flag OPENSSL_ZERO_PADDING as fourth parameter in the openssl_encrypt method (note: that flag doesn't mean "pad with zero-values", but "no padding"). If the custom padding is kept, you should at least rename the PHP-methods encrypt and decrypt to pad and unpad (or something similar), respectively.
As stated already in the comments, the GCM-mode may be a better choice than the-CBC mode. However, it would be useful to get informed about the basics before coding, e.g. difference between CBC- and GCM-mode,
explanation of the GCM-mode here and here and the pitfalls coming along with the GCM-mode (GCM is secure, but only if you follow certain guidelines, e.g. a uniqe IV/nonce for each message encrypted with the same key).
You can use the PHP-method openssl_get_cipher_methods to find out the permissible AES-modes supported in PHP. This is explained in more detail here. For AES-256 and the AES-mode GCM you have to specify aes-256-gcm (with lowercase(!) letters). Presumably, that's why you get the "Unknown cipher algorithm"-error.
EDIT:
You can use for the encryption the following PHP-code (which is a slightly modified version of your PHP-code from the question):
<?php
function pad($data, $size) {
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
function unpad($data) {
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
$data = 'This is a plain text which needs to be encrypted...';
$key = "SiadajerSiadajer";
$iv_size = 16;
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
$encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key, 0, $iv);
print base64_encode($iv)."\n".$encryptedData."\n";
EDIT 2:
The IV and the encrypted data can be joined before or after the Base64-encoding. The first is more efficient and thus, I've implemented this variant. However, some changes are needed in the PHP- and Java-code and therefore, I post all methods which have changed.
The PHP-code becomes:
<?php
function pad($data, $size) {
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
function unpad($data) {
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
$data = 'This is a plain text which needs to be encrypted...';
$key = "SiadajerSiadajer";
$iv_size = 16;
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
$encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
$joinedData = $iv.$encryptedData;
$encodedJoinedData = base64_encode($joinedData);
print $encodedJoinedData."\n";
And the Jave-method decrypt becomes:
public String decrypt(String encodedJoinedData) throws Exception {
// Base64-decode the joined data
byte[] joinedData = Base64.decode(encodedJoinedData);
// Get IV and encrypted data
byte[] iv = new byte[16];
System.arraycopy(joinedData, 0, iv, 0, iv.length);
byte[] encryptedData = new byte[joinedData.length - iv.length];
System.arraycopy(joinedData, iv.length, encryptedData, 0, encryptedData.length);
// Pad key
byte[] key = padKey("SiadajerSiadajer".getBytes());
Key aesKey = new SecretKeySpec(key, "AES");
// Specify CBC-mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
// Decrypt data
byte[] decryptedData = cipher.doFinal(encryptedData);
// Remove custom padding
byte[] unpaddedData = unpad(decryptedData);
return new String(unpaddedData);
}
and an example for the Java-method main is:
public static void main(String[] args) throws Exception {
String encodedJoinedData = "RB6Au33KGOF1/z3BQKqievUmh81Y8q4uw7s4vEs9xurQmNZAKwmhRQtS9wGYKQj8cJaPpK2xaDzx3RppQ8PsM/rQ9/p0Lme+x75dozBEbmFn6Q9eCXOCiCivVsKzZ8Vz";
String decryptedData = new Main().decrypt(encodedJoinedData);
System.out.println(decryptedData + " - " + decryptedData.length());
}
The usage is as follows:
Encrypt your plain text with the PHP-code. In the example above (PHP-code) the plain text is
$data = 'This is a plain text which needs to be encrypted...';
Then, pass the string contained in $encodedJoinedData to the Java-method decrypt. In the example above (main-method) the string is
String encodedJoinedData = "RB6Au33KGOF1/z3BQKqievUmh81Y8q4uw7s4vEs9xurQmNZAKwmhRQtS9wGYKQj8cJaPpK2xaDzx3RppQ8PsM/rQ9/p0Lme+x75dozBEbmFn6Q9eCXOCiCivVsKzZ8Vz";
The Java-method decrypt will provide the initial plain text.
A final note: If you decide to remove the (redundant) custom padding replace in the PHP-code the line
$encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
with
$encryptedData = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
and remove the pad- and the unpad-method.
In the Java-code replace the lines
// Remove custom padding
byte[] unpaddedData = unpad(decryptedData);
return new String(unpaddedData);
with
return new String(decryptedData);
and remove the unpad-method.
Edit 3:
The InvalidKeyException (Illegal key size) mentioned in the Edit2-section of the question is already discussed e.g. here InvalidKeyException Illegal key size and here Java Security: Illegal key size or default parameters?.

How to decrypt a cipher text using Java which is encrypted with Rijndael-256 with custom IV?

I have found a source code at stackoverflow on Rinjndael-256 encryption and decryption written in c#. It is using custom IV appending some extra string. Now I need a decryption method on Java platform. I have found some source code; tried to change and test that. Here is the encryption method on c#:
public static string Encrypt(byte[] text, string key)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Padding = PaddingMode.None;
aes.Mode = CipherMode.CBC;
aes.Key = Encoding.Default.GetBytes(key);
aes.GenerateIV();
string IV = ("-[--IV-[-" + Encoding.Default.GetString(aes.IV));
ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] buffer = text;
return Convert.ToBase64String(Encoding.Default.GetBytes(Encoding.Default.GetString(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + IV));
}
The decryption method on java which is not working for me is:
public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(cipher.doFinal(cipherText),"UTF-8");
}
Edit 1:
I have implemented the php code for decryption.
function decrypt($text, $pkey)
{
$key = $pkey;
$text = base64_decode($text);
$IV = substr($text, strrpos($text, "-[--IV-[-") + 9);
$text = str_replace("-[--IV-[-" . $IV, "", $text);
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $IV), "\0");
}
Is there any manual way of implementing Rijndael-256 in Java? As someone said that
There is no support in any of the Sun JCE providers for anything other than Rijndael with the 128-bit blocksize
I don't have an option to use library

Migrate openssl to java

I need to migrate a crypto package from C++/openssl to pure java implementation. However, I am having some issues that I don't know how to solve.
Below is a C++ list that outlines a decryption scheme that I am currently trying to migrate.
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
// set master key
AES_KEY master_key;
const int AES128_KEY_SIZE = 16;
unsigned char* master_secret = "averysecretmastersecret";
AES_set_encrypt_key(master_secret, AES128_KEY_SIZE * 8 , &master_key);
// Base64 decode; encryptedInput is the original input text
// b64_output consists of two parts: a leading salt (16 bytes) and the following actual data
char* b64_output = base64Decode(encryptedInput); // base64Decode(const char* encodedText) -> char* decodedText
// prepare salt
const char SALT_LEN = 16; // first byte is reserved. Actually only use 15 bytes = 120 bit
unsigned char salt[SALT_LEN];
memcpy(salt, b64_output, SALT_LEN); // read salt
// generate key
const int AES128_KEY_SIZE = 16;
unsigned char key[AES128_KEY_SIZE];
salt[0] = 1; //
AES_ecb_encrypt(salt, key, &master_key, AES_ENCRYPT);
// generate iv
const int AES128_IV_SIZE = 16;
unsigned char iv[AES128_IV_SIZE];
salt[0] = 2; // ensure that key and iv are different
AES_ecb_encrypt(salt, iv, &master_key, AES_ENCRYPT);
// initialize cipher context
EVP_CIPHER_CTX *de;
de = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(de);
EVP_DecryptInit_ex(de, EVP_aes_128_cbc(), NULL, key, iv)
aes_decrypt(b64_output + SALT_LEN, length - SALT_LEN);
// plaintext is a buffer to contain the output
int plaintext_size = DEFAULT_BUFFER_SIZE;
char *plaintext = (char*)malloc(plaintext_size);
int aes_decrypt(const char *ciphertext, int len)
{
int p_len = len, f_len = 0;
// allocate an extra cipher block size of memory because padding is ON
// #define AES_BLOCK_SIZE 16
if(p_len + AES_BLOCK_SIZE > plaintext_size) {
ASSERT_CALL(enlarge_buffer(plaintext, plaintext_size, p_len + AES_BLOCK_SIZE), "enlarge plaintext buffer failed");
}
ASSERT_OPENSSL( EVP_DecryptInit_ex(de, NULL, NULL, NULL, NULL), "sets up decode context failed");
ASSERT_OPENSSL( EVP_DecryptUpdate(de, (unsigned char*)plaintext, &p_len, (unsigned char*)ciphertext, len), "decrypt failed");
EVP_DecryptFinal_ex(de, (unsigned char*)plaintext+p_len, &f_len);
return EY_SUCCESS;
}
EVP_CIPHER_CTX_free(de);
dec_result = std::string(plaintext);
Below is a java code list that I currently have (not working, of course) to reproduce above C++ logic:
String encrypted = "AtUKTnCF18kFTJIycg/RXKJ82IVCtaa+eKNVl8FhT0k+wvpc+cBIs5jb/QlLRMf4";
String secret = "averysecretmastersecret";
int SALT_LEN = 16;
String keyAlgorithm = "AES";
String ECB_TRANSFORM = "AES/ECB/NoPadding";
String CBC_TRANSFORM = "AES/CBC/NoPadding";
byte[] bytesOfSecret = Arrays.copyOf(secret.getBytes(), 16);
Key key =new SecretKeySpec(bytesOfSecret, keyAlgorithm);
Cipher ecbCipher = Cipher.getInstance(ECB_TRANSFORM);
Cipher cbcCipher = Cipher.getInstance(CBC_TRANSFORM);
// decode
byte[] decoded = Base64.getDecoder().decode(encrypted);
byte[] salt = Arrays.copyOf(decoded, SALT_LEN);
byte[] data = Arrays.copyOfRange(decoded, SALT_LEN, decoded.length);
// get iv
salt[0] = 2;
ecbCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] iv = ecbCipher.doFinal(salt);
iv = Arrays.copyOf(iv, 16);
AlgorithmParameterSpec parameterSpec = new IvParameterSpec(iv);
cbcCipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
byte[] bytes = cbcCipher.doFinal(data);
String decrypted = new String(bytes);
System.out.println(decrypted);
There are a couple places that I don't know how to map from C++ to java right now. First, in the C++ code, it uses a salt to generate a key and an iv, which are subsequently used to initialize EVP cipher context as in EVP_DecryptInit_ex(de, EVP_aes_128_cbc(), NULL, key, iv). I don't know the equivalent operation in java.
Second, there is no direct mentioning in the C++ code whether padding is used. I tried both NoPadding and PKCS5Padding, but not sure which one is the right one.
So, how can I reproduce the C++ logic in java? Is there any example out there?
update
I also tried BouncyCastle. It is still not working. Below is my code:
int SALT_LEN = 16;
String encrypted = "AtUKTnCF18kFTJIycg/RXKJ82IVCtaa+eKNVl8FhT0k+wvpc+cBIs5jb/QlLRMf4";
String password = "averysecretmastersecret";
// decode
byte[] decoded = Base64.getDecoder().decode(encrypted);
byte[] salt = Arrays.copyOf(decoded, SALT_LEN);
byte[] data = Arrays.copyOfRange(decoded, SALT_LEN, decoded.length);
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
PBEParametersGenerator generator = new OpenSSLPBEParametersGenerator();
byte[] bytesOfSecret = PBEParametersGenerator.PKCS5PasswordToBytes(password.toCharArray());
generator.init(bytesOfSecret, salt, 1);
ParametersWithIV parametersWithIV = (ParametersWithIV) generator.generateDerivedParameters(128, 128);
// for decryption
cipher.init(false, parametersWithIV);
byte[] decrypted = new byte[cipher.getOutputSize(data.length)];
System.out.println("expected decrypted size = " + decrypted.length); // prints ... size = 32
int processedBytes = cipher.processBytes(data, 0, data.length, decrypted, 0);
System.out.println("processed bytes = " + processedBytes); // prints ... bytes = 16
cipher.doFinal(decrypted, processedBytes); // Line 59, run into exception
String output = new String(decrypted);
System.out.println(output);
Line 59, as marked above, gives this exception:
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(Unknown Source)
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(Unknown Source)
...
This is an example of java AES encryption i hope this helps
String key = "HkJHBKJBvffdbv";
String IV= "qjfghftrsbdghzir";
String theMessageToCifer ="your message";
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
try{
//specify your mode
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivSpec);
encrypted = cipher.doFinal(theMessageToCifer.getBytes());
bytesEncoded = Base64.encode(encrypted);
System.out.println(" base64 code " +bytesEncoded);
System.out.println("encrypted string: " +encrypted);
// decryption
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec,ivSpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " + originalString );
}catch (Exception e){
e.printStackTrace();
}

Java encrypt/decript data from PHP to Java, IllegalBlockSizeException

I'm trying to read a base64 encoded and AES 128-bit encrypted string from PHP, but I'm getting IllegalBlockSizeException.
PHP encrypt:
encrypt("My f awesome test !");
function encrypt($string){
$td = mcrypt_module_open('rijndael-128', '', 'cbc', "1cc251f602cf49f2");
mcrypt_generic_init($td, "f931c96c4a4e7e47", "1cc251f602cf49f2");
$enc = mcrypt_generic($td, $string);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($enc);
}
And the returned value is:
McBeY73GQ5fawxIunVKpqUupipeRlt9ntyMRzjbPfTI=
Now I want to read it in Java:
static public String decrypt(String data) throws Exception {
data = new String( Base64.decode(data, Base64.NO_WRAP) );
byte[] keyByte = "f931c96c4a4e7e47".getBytes("UTF-8");
byte[] ivByte = "1cc251f602cf49f2".getBytes("UTF-8");
Key key = new SecretKeySpec(keyByte, "AES");
IvParameterSpec iv = new IvParameterSpec(ivByte);
Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, iv);
byte[] bval = c.doFinal( data.getBytes("UTF-8") );
return new String( bval );
}
And I'm getting an Exception:
javax.crypto.IllegalBlockSizeException: data not block size aligned
This might be caused by padding?
EDIT
Your error was caused by the conversion of the plaintext to and from a string. It's not necessary anyway - just use byte arrays:
byte[] data = Base64
.decodeBase64("McBeY73GQ5fawxIunVKpqUupipeRlt9ntyMRzjbPfTI=");
byte[] keyByte = "f931c96c4a4e7e47".getBytes("UTF-8");
byte[] ivByte = "1cc251f602cf49f2".getBytes("UTF-8");
Key key = new SecretKeySpec(keyByte, "AES");
IvParameterSpec iv = new IvParameterSpec(ivByte);
Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, iv);
byte[] bval = c.doFinal(data);
System.out.println(new String(bval)); // Prints My f awesome test !
I recommend you use padding in your encryption, otherwise you cannot cope with arbitrarily-sized input.
the IllegalBlockSizeException thrown on call to doFinal() if: "cipher is a block cipher, no padding has been requested (only in encryption mode), and the total input length of the data processed by this cipher is not a multiple of block size; or if this encryption algorithm is unable to process the input data provided." -http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html#doFinal%28%29. So its either bad input data or block size.
This is a working version of encryption/decryption between
https://github.com/chaudhuri-ab/CrossPlatformCiphers
Hope this helps someone as it took me a while to work through the little details between the platforms.

PHP Equivalent for Java Triple DES encryption/decryption

Am trying to decrypt a key encrypted by Java Triple DES function using PHP mcrypt function but with no luck. Find below the java code
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Encrypt3DES {
private byte[] key;
private byte[] initializationVector;
public Encrypt3DES(){
}
public String encryptText(String plainText, String key) throws Exception{
//---- Use specified 3DES key and IV from other source --------------
byte[] plaintext = plainText.getBytes();
byte[] myIV = key.getBytes();
byte[] tdesKeyData = {(byte)0xA2, (byte)0x15, (byte)0x37, (byte)0x08, (byte)0xCA, (byte)0x62,
(byte)0xC1, (byte)0xD2, (byte)0xF7, (byte)0xF1, (byte)0x93, (byte)0xDF,
(byte)0xD2, (byte)0x15, (byte)0x4F, (byte)0x79, (byte)0x06, (byte)0x67,
(byte)0x7A, (byte)0x82, (byte)0x94, (byte)0x16, (byte)0x32, (byte)0x95};
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(myIV);
c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);
sun.misc.BASE64Encoder obj64=new sun.misc.BASE64Encoder();
return obj64.encode(cipherText);
}
public String decryptText(String encryptText, String key) throws Exception{
byte[] initializationVector = key.getBytes();
byte[] tdesKeyData = {(byte)0xA2, (byte)0x15, (byte)0x37, (byte)0x08, (byte)0xCA, (byte)0x62,
(byte)0xC1, (byte)0xD2, (byte)0xF7, (byte)0xF1, (byte)0x93, (byte)0xDF,
(byte)0xD2, (byte)0x15, (byte)0x4F, (byte)0x79, (byte)0x06, (byte)0x67,
(byte)0x7A, (byte)0x82, (byte)0x94, (byte)0x16, (byte)0x32, (byte)0x95};
byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(encryptText);
Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(initializationVector);
decipher.init(Cipher.DECRYPT_MODE, myKey, ivspec);
byte[] plainText = decipher.doFinal(encData);
return new String(plainText);
}
}
I want to write a PHP function equivalent to the decryptText Java function above. am finding difficulty in generating the exact IV value generated by the Java code for encryption, which is required for the decryption.
This is the PHP equivalent of your Java code (I have copied the PKCS#5-padding from the comment 20-Sep-2006 07:56 of The mcrypt reference)
function encryptText($plainText, $key) {
$keyData = "\xA2\x15\x37\x08\xCA\x62\xC1\xD2"
. "\xF7\xF1\x93\xDF\xD2\x15\x4F\x79\x06"
. "\x67\x7A\x82\x94\x16\x32\x95";
$padded = pkcs5_pad($plainText,
mcrypt_get_block_size("tripledes", "cbc"));
$encText = mcrypt_encrypt("tripledes", $keyData, $padded, "cbc", $key);
return base64_encode($encText);
}
function decryptText($encryptText, $key) {
$keyData = "\xA2\x15\x37\x08\xCA\x62\xC1\xD2"
. "\xF7\xF1\x93\xDF\xD2\x15\x4F\x79\x06"
. "\x67\x7A\x82\x94\x16\x32\x95";
$cipherText = base64_decode($encryptText);
$res = mcrypt_decrypt("tripledes", $keyData, $cipherText, "cbc", $key);
$resUnpadded = pkcs5_unpad($res);
return $resUnpadded;
}
function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
But there are some problems you should be aware of:
In your Java code you call String.getBytes() without indicating an encoding. This makes your code non portable if your clear text contains non ASCII-characters such as umlauts, because Java uses the system-default character set. If you can change that I certainly would do so. I recommend you to use utf-8 on both sides (Java and PHP).
You have hard coded the cipher-key and use the IV as "key". I'm by no means a crypto-expert but to me it just feels wrong and may open a huge security leak.
Create a random IV and just concatenate it at the start or at the end of your message. Since the size of the IV is AFAIK equal to the block-size of your cipher you just remove that much bytes from the start or end and have easily separated the IV from the message.
As for the key, it's best to use some kind of key derivation method to generate a key with the right size from a "human generated" password.
Of course, if you have to fulfil some given requirements you can't change your method.
The answer is almost good! Just reverse $keyData and $key in
$encText = mcrypt_encrypt("tripledes", $keyData, $padded, "cbc", $key);
and
$res = mcrypt_decrypt("tripledes", $keyData, $cipherText, "cbc", $key);
otherwise you will always use the same 3DES key. And it's better to rename $keyData to $iv.
Anyway, thanks a lot for the Java sample and the Php-Java translation.

Categories