Aes encryption on Android(client) and Decryption on Server with C++ - java

I am working with AES encryption on my android application and I have a problem. I want my application to encrypt a password using Aes_256_Cbc algorithm. The encrypted string must be different each time that's why I need a truly random iv each time. The code I have to encrypt the word is:
import android.content.Context;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Encryptor
{
Context context;
private static final String WORD = "aefbjolpigrschnx";
private static final String KEY = "kumyntbrvecwxasqertyplmqazwsxedc";
private final static String HEX = "0123456789ABCDEF";
public Encryptor(Context c)
{
context = c;
}
public String getEncryptedPasswd()
{
String ivHex = "";
String encryptedHex = "";
try
{
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[16];
random.nextBytes(iv);
ivHex = toHex(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
Cipher encryptionCipher = Cipher.getInstance("AES/CBC");
encryptionCipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
byte[] encryptedText = encryptionCipher.doFinal(WORD.getBytes("UTF-8"));
encryptedHex = toHex(encryptedText);
}
catch (Exception e)
{
}
return ivHex + encryptedHex;
}
public static String toHex(byte[] buf)
{
if (buf == null)
{
return "";
}
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++)
{
result.append(HEX.charAt((buf[i]>>4)&0x0f)).append(HEX.charAt(buf[i]&0x0f));
}
return result.toString();
}
My application calls the function getEncryptedPasswd() several times, each time it gives a different hex output, as expected. Then it sends the encrypted password to the server where my code must be in C++. But when I try to decrypt the password using openssl I don't take the correct output. Can anyone help me? My code at the server is:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <openssl/aes.h>
#define KEY "kumyntbrvecwxasqertyplmqazwsxedc"
using namespace std;
unsigned int hex2bin(char *ibuf, unsigned char *obuf, unsigned int ilen)
{
unsigned int i;
unsigned int j;
unsigned int by = 0;
unsigned char ch;
// process the list of characaters
for (i = 0; i < ilen; i++)
{
ch = toupper(*ibuf++);
// do the conversion
if(ch >= '0' && ch <= '9')
{
by = (by << 4) + ch - '0';
}
else if(ch >= 'A' && ch <= 'F')
{
by = (by << 4) + ch - 'A' + 10;
}
else
{
memcpy(obuf, "ERROR", 5);
return 0;
}
// store a byte for each pair of hexadecimal digits
if (i & 1)
{
j = ((i + 1) / 2) - 1;
obuf[j] = by & 0xff;
}
}
return (j+1);
}
string iv_str = auth.substr(0, 16);
string enc_str = auth.substr(16);
char *iv_buf = new char [iv_str.length() + 1];
strcpy(iv_buf, iv_str.data());
char *enc_buf = new char [enc_str.length() + 1];
strcpy(enc_buf, enc_str.data());
unsigned long ilen;
unsigned char iv[16];
unsigned char enc_word[16]; // hex decrypt output
unsigned char word[16]; // decrypt output
unsigned char enc_key[] = KEY;
AES_KEY aeskeyDec;
AES_set_decrypt_key(enc_key, 256, &aeskeyDec);
ilen = hex2bin(enc_buf, enc_word, (int) strlen(enc_buf));
hex2bin(iv_buf, iv, (int) strlen(iv_buf));
AES_cbc_encrypt(enc_word, word, ilen, &aeskeyDec, iv, AES_DECRYPT);

I'm a C++ guy, not java, so I cannot comment on this line of yours other than to say that it looks like it would do what you need:
Cipher encryptionCipher = Cipher.getInstance("AES/CBC");
But just in case there is more to it, note that I can confirm that Java by default uses ECB mode. Like yourself, I also had to AES decrypt in C++ some text that had been encrypted in Java. Took me a while to figure out what was happening: how to use OpenSSL to decrypt Java AES-encrypted data?

Related

Mismatch in result when encrypting in AES for Java and Golang

I'm using this code in Java to generate the cipher text using simple AES algorithm:
public String encrypt(String message, String key) {
skeySpec = new SecretKeySpec(HexUtil.HexfromString(key), "AES");
cipher = Cipher.getInstance("AES");
cipher.init(1, skeySpec);
byte encstr[] = cipher.doFinal(message.getBytes());
return HexUtil.HextoString(encstr);
}
And the function HexfromString is:
public static byte[] HexfromString(String s) {
int i = s.length();
byte[] byte0 = new byte[(i + 1) / 2];
int j = 0;
int k = 0;
if (i % 2 == 1) byte0[k++] = (byte) HexfromDigit(s.charAt(j++));
while (j < i) {
int v1 = HexfromDigit(s.charAt(j++)) << 4;
int v2 = HexfromDigit(s.charAt(j++));
byte0[k++] = (byte) (v1 | v2);
}
return byte0;
}
I wrote the following code in Golang to mimic the above result.
func EncryptAES(secretKey string, plaintext string) string {
key := hex.DecodeString(secretKey)
c, err := aes.NewCipher(key)
CheckError(err)
out := make([]byte, len(plaintext))
c.Encrypt(out, []byte(plaintext))
return hex.EncodeToString(out)
}
But the issue is that the []bytes key returned from hex.DecodeString() is in unsigned Int where as in Java, the result is in signed Int. And obviously, the encrypted text results are also different, even though every input is same.

MbedTLS AES 128 encrypt and decrypt in Java

I am trying to encrypt some text on microprocessor running FreeRTOS with mbedTLS. I am using AES 128 CBC with PKCS7 padding. If I try to encrypt in mbedTLS and decrypt in Java when text is shorter than 16 characters it works. I can decrypt it in Java and the text matches. If it is longer then it no longer works. What am I doing wrong?
mbedTLS code:
unsigned char key[17] = "asdfghjklqwertzu";
unsigned char iv[17] = "qwertzuiopasdfgh";
unsigned char output[1024];
size_t olen;
size_t total_len = 0;
mbedtls_cipher_context_t ctx;
mbedtls_cipher_init(&ctx);
mbedtls_cipher_set_padding_mode(&ctx, MBEDTLS_PADDING_PKCS7);
mbedtls_cipher_setup(&ctx,
mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, 128,
MBEDTLS_MODE_CBC));
mbedtls_cipher_setkey(&ctx, key, 128, MBEDTLS_ENCRYPT);
mbedtls_cipher_set_iv(&ctx, iv, 16);
mbedtls_cipher_reset(&ctx);
char aa[] = "hello world! test long padd";
for( int offset = 0; offset < strlen(aa); offset += mbedtls_cipher_get_block_size( &ctx ) ) {
int ilen = ( (unsigned int) strlen(aa) - offset > mbedtls_cipher_get_block_size( &ctx ) ) ?
mbedtls_cipher_get_block_size( &ctx ) : (unsigned int) ( strlen(aa) - offset );
char sub[100];
strncpy ( sub, aa+offset, ilen );
unsigned char* sub2 = reinterpret_cast<unsigned char *>(sub);
mbedtls_cipher_update(&ctx, sub2, ilen, output, &olen);
total_len += olen;
}
// After the loop
mbedtls_cipher_finish(&ctx, output, &olen);
total_len += olen;
mbedtls_cipher_free(&ctx);
Java code:
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
SecretKeySpec skey = new SecretKeySpec(encryptionKey.getBytes(), "AES");
Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, skey, ivParameterSpec);
return Optional.ofNullable(ByteString.copyFrom(cipherDecrypt.doFinal(message.toByteArray())));
} catch (BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
log.error("Error during message decryption: ", e);
}
Java throws javax.crypto.BadPaddingException: pad block corrupted
Thanks
// EDIT:
Tried with one update approach and still no luck, the same exception:
unsigned char key[17] = "asdfghjklqwertzu";
unsigned char iv[17] = "qwertzuiopasdfgh";
//unsigned char buffer[1024];
unsigned char output[1024];
size_t olen;
unsigned char text[] = "abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc";
mbedtls_cipher_context_t ctx;
mbedtls_cipher_init(&ctx);
mbedtls_cipher_set_padding_mode(&ctx, MBEDTLS_PADDING_PKCS7);
mbedtls_cipher_setup(&ctx,
mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, 128,
MBEDTLS_MODE_CBC));
mbedtls_cipher_setkey(&ctx, key, 128, MBEDTLS_ENCRYPT);
mbedtls_cipher_set_iv(&ctx, iv, 16);
mbedtls_cipher_reset(&ctx);
mbedtls_cipher_update(&ctx, text, strlen((char*) text), output, &olen); // Olen is 48
mbedtls_cipher_finish(&ctx, output, &olen); // Olen is 16
mbedtls_cipher_free(&ctx);
// 48 + 16 = 64 which is according to https://www.devglan.com/online-tools/aes-encryption-decryption correct
Java gets a 64 bytes of data but still throws the same exception.
Topaco please can you provide short example of usage of update and finish functions? Thank you
Since it was written in comments that it still doesn't work. Here your code with the changes suggested by #Topaco in the comments:
#include <stdio.h>
#include <string.h>
#include <mbedtls/cipher.h>
int main() {
unsigned char key[17] = "asdfghjklqwertzu";
unsigned char iv[17] = "qwertzuiopasdfgh";
unsigned char output[1024];
size_t olen;
size_t total_len = 0;
mbedtls_cipher_context_t ctx;
mbedtls_cipher_init(&ctx);
mbedtls_cipher_set_padding_mode(&ctx, MBEDTLS_PADDING_PKCS7);
mbedtls_cipher_setup(&ctx,
mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, 128,
MBEDTLS_MODE_CBC));
mbedtls_cipher_setkey(&ctx, key, 128, MBEDTLS_ENCRYPT);
mbedtls_cipher_set_iv(&ctx, iv, 16);
mbedtls_cipher_reset(&ctx);
char aa[] = "hello world! test long padd";
for (int offset = 0; offset < strlen(aa); offset += mbedtls_cipher_get_block_size(&ctx)) {
int ilen = ((unsigned int) strlen(aa) - offset > mbedtls_cipher_get_block_size(&ctx)) ?
mbedtls_cipher_get_block_size(&ctx) : (unsigned int) (strlen(aa) - offset);
char sub[100];
strncpy (sub, aa + offset, ilen);
unsigned char *sub2 = (unsigned char *) (sub);
mbedtls_cipher_update(&ctx, sub2, ilen, output + total_len, &olen);
total_len += olen;
}
mbedtls_cipher_finish(&ctx, output + total_len, &olen);
total_len += olen;
for (int i = 0; i < total_len; i++)
printf("%02X", output[i]);
mbedtls_cipher_free(&ctx);
return 0;
}
Test
I added two additional lines:
for (int i = 0; i < total_len; i++)
printf("%02X", output[i]);
This gives the output:
2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0
If I modify Java side a bit and transfer message with:
byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");
where hexStringToByteArray is taken from this answer: https://stackoverflow.com/a/140861/2331445
I get on Java side the following code:
public Optional<ByteString> test() {
String encryptionKey = "asdfghjklqwertzu";
String iv = "qwertzuiopasdfgh";
byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");
Security.addProvider(new BouncyCastleProvider());
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
SecretKeySpec skey = new SecretKeySpec(encryptionKey.getBytes(), "AES");
Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, skey, ivParameterSpec);
return Optional.ofNullable(ByteString.copyFrom(cipherDecrypt.doFinal(message)));
} catch (BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
System.out.println("Error during message decryption: " + e);
}
return null;
}
which finally gives the following output onto the debug console:
Optional[<ByteString#1e127982 size=27 contents="hello world! test long padd">]
That is the original message - so this way it works.
There is still one issue left in your code.
You will need to setup cipher info before setting padding mode. Otherwise function
mbedtls_cipher_set_padding_mode will return an error

Java 256-bit AES Encryption

I need to implement 256 bit AES encryption for cash flow i have c# answer but the answer is not the same,for a newbie, I am not sure if my direction is correct.
this is my code
public static void main(String[] args) {
String key = "12345678901234567890123456789012";
String hashIv = "1234567890123456";
String value = "MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest";
String result = encrypt(key, hashIv, value);
System.out.println(result);
System.out.println();
String sha256 = encrySha256("HashKey=" + key + "&" + result + "&HashIV=" + hashIv);
System.out.println(sha256.trim());
}
public static String encrypt(String hashKey, String hashIv, String text) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(hashKey.getBytes("UTF-8"), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(hashIv.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal((text.getBytes("UTF-8")));
String test = bytesToHex(encrypted);
return test.toLowerCase();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public static String bytesToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static String encrySha256(String value) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(value.getBytes());
byte byteBuffer[] = messageDigest.digest();
StringBuffer strHexString = new StringBuffer();
for (int i = 0; i < byteBuffer.length; i++) {
String hex = Integer.toHexString(0xff & byteBuffer[i]);
if (hex.length() == 1) {
strHexString.append('0');
}
strHexString.append(hex);
}
return strHexString.toString().toUpperCase();
} catch (Exception e) {
}
return null;
}
sample encrypt answer :
ff91c8aa01379e4de621a44e5f11f72e4d25bdb1a18242db6cef9ef07d80b0165e476fd1d
9acaa53170272c82d122961e1a0700a7427cfa1cf90db7f6d6593bbc93102a4d4b9b66d9
974c13c31a7ab4bba1d4e0790f0cbbbd7ad64c6d3c8012a601ceaa808bff70f94a8efa5a4f
984b9d41304ffd879612177c622f75f4214fa
encryptSha256 answer : EA0A6CC37F40C1EA5692E7CBB8AE097653DF3E91365E6A9CD7E91312413C7BB8
this is c# code and this is sample data
[MerchantID] => 3430112 [RespondType] => JSON [TimeStamp] => 1485232229
[Version] => 1.4 [MerchantOrderNo] => S_1485232229 [Amt] => 40 [ItemDesc] =>
UnitTest
public string EncryptAES256(string source)//加密
{
string sSecretKey = "12345678901234567890123456789012";
string iv = "1234567890123456";
byte[] sourceBytes =
AddPKCS7Padding(Encoding.UTF8.GetBytes(source), 32);
var aes = new RijndaelManaged();
aes.Key = Encoding.UTF8.GetBytes(sSecretKey);
aes.IV = Encoding.UTF8.GetBytes(iv);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
ICryptoTransform transform = aes.CreateEncryptor();
return ByteArrayToHex(transform.TransformFinalBlock(sourceBytes, 0,
sourceBytes.Length)).ToLower();
}
private static byte[] AddPKCS7Padding(byte[] data, int iBlockSize)
{
int iLength = data.Length;
byte cPadding = (byte)(iBlockSize - (iLength % iBlockSize));
var output = new byte[iLength + cPadding];
Buffer.BlockCopy(data, 0, output, 0, iLength);
for (var i = iLength; i < output.Length; i++)
output[i] = (byte)cPadding;
return output;
}
private static string ByteArrayToHex(byte[] barray)
{
char[] c = new char[barray.Length * 2];
byte b;
for (int i = 0; i < barray.Length; ++i)
{
b = ((byte)(barray[i] >> 4));
c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(barray[i] & 0xF));
c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new string(c);
}
The reason for the different encrypted data is that you compare different plain texts. In your Java code you encrypt the plain text
MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest
and you compare the encrypted data with your reference data
ff91c8aa01379e4de621a44e5f11f72e4d25bdb1a18242db6cef9ef07d80b0165e476fd1d9acaa53170272c82d122961e1a0700a7427cfa1cf90db7f6d6593bbc93102a4d4b9b66d9974c13c31a7ab4bba1d4e0790f0cbbbd7ad64c6d3c8012a601ceaa808bff70f94a8efa5a4f984b9d41304ffd879612177c622f75f4214fa
However, these reference data correspond to a different plain text. The latter you can easily derive by decrypting the reference data with the C# DecryptAES256-method which provides
MerchantID=3430112&RespondType=JSON&TimeStamp=1485232229&Version=1.4&MerchantOrderNo=S_1485232229&Amt=40&ItemDesc=UnitTest
Here, in contrast to the plain text in your Java code, a &-delimiter is used.
If you use the same plain text the Java encrypt- and the C# EncryptAES256-method provide the same encrypted data (same key, IV and padding supposed; for the latter see EDIT-section).
In the following testcase the plain text from your Java code is used:
encrypt("12345678901234567890123456789012", "1234567890123456", "MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest")
and
EncryptAES256("MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest")
both provide the encrypted data:
ff91c8aa01379e4de621a44e5f11f72ef45b7b9f9663d386da51af13f7f3b8f2b1ed4a3b7ac6b7783402193ea1d766e3046b6acf612d62568ccdbc475e5a14d114273735b069464dcc8281f4e5bf8486eb97d31602c3fe79cfe7140d2848413edad9d96fabf54d103f3d7a9b401c83fa5e4f17b10a280df10b3d61f23e69bbb8
which (as expected) differs from your reference data (with the exception of the first block).
EDIT
There is a second issue concerning the padding: Your C# EncryptAES256-method uses a custom padding provided by the C# AddPKCS7Padding-method which pads to a multiple of 32 bytes.
In contrast, your Java encrypt-method uses PKCS5Padding which pads to a multiple of 16 bytes.
Thus, the encrypted data of the Java encrypt- and the C# EncryptAES256-method differ if the length of the plain text is between 16 * n byte and 16 * (n + 1) - 1 byte with even n (0,2,4,...).
For odd n (1,3,5,...) the encrypted data are identical. In the example above the byte array of the plain text has 116 bytes that is n = 7 (112 <= 116 <= 127) and therefore the encrypted data are the same.
If the Java encrypt-method should use the same padding as the C# EncryptAES256-method you additionally have to implement an analogous Java-method e.g.:
private static byte[] addPKCS7Padding(byte[] data, int iBlockSize)
{
int iLength = data.length;
byte cPadding = (byte)(iBlockSize - (iLength % iBlockSize));
byte[] output = new byte[iLength + cPadding];
System.arraycopy(data, 0, output, 0, iLength);
for (int i = iLength; i < output.length; i++)
output[i] = (byte)cPadding;
return output;
}
and in the Java encrypt-method you have to replace:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
with
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
and also
byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));
with
byte[] encrypted = cipher.doFinal(addPKCS7Padding(text.getBytes("UTF-8"), 32));
before:
MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest
After:
MerchantID=3430112&RespondType=JSON&TimeStamp=1485232229&Version=1.4&MerchantOrderNo=S_1485232229&Amt=40&ItemDesc=UnitTest
I only add "&" with each parameter, it's work!!!!
try it!!!
(我只加了&就成功拉,你的代碼沒問題,只是參數要加&而已)

AES Initialization Vector randomization

I am trying to reuse an AES implementation with Initialization Vector. So far I am only implementing the part where data is being encrypted on the android application and being decrypted on the php server. However, the algorithm has a major loophole, that the Initialization Vector is constant, which I just recently found out is a major security flaw. Unfortunately I have already implemented it on every single activity of my application and all scripts on the server side.
I wanted to know if there was a way to modify this code so that the initialization vector is randomized, and some way to send that vector to the server (or vice versa), so that every time the message is encrypted the pattern keeps changing. Here are my codes for Android and PHP:
Android:
package com.fyp.merchantapp;
// This file and its contents have been taken from http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php.html
//Ownership has been acknowledged
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MCrypt {
static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private String iv = "MyNameIsHamza100";//(IV)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "MyNameIsBilal100";//(SECRETKEY)
public MCrypt()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
//Remove trailing zeroes
if( decrypted.length > 0)
{
int trim = 0;
for( int i = decrypted.length - 1; i >= 0; i-- ) if( decrypted[i] == 0 ) trim++;
if( trim > 0 )
{
byte[] newArray = new byte[decrypted.length - trim];
System.arraycopy(decrypted, 0, newArray, 0, decrypted.length - trim);
decrypted = newArray;
}
}
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] buf)
{
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
private static String padString(String source)
{
char paddingChar = 0;
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}
return source;
}
}
PHP:
<?php
class MCrypt
{
private $iv = 'MyNameIsHamza100'; #Same as in JAVA
private $key = 'MyNameIsBilal100'; #Same as in JAVA
function __construct()
{
}
/**
* #param string $str
* #param bool $isBinary whether to encrypt as binary or not. Default is: false
* #return string Encrypted data
*/
function encrypt($str, $isBinary = false)
{
$iv = $this->iv;
$str = $isBinary ? $str : utf8_decode($str);
$td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $isBinary ? $encrypted : bin2hex($encrypted);
}
/**
* #param string $code
* #param bool $isBinary whether to decrypt as binary or not. Default is: false
* #return string Decrypted data
*/
function decrypt($code, $isBinary = false)
{
$code = $isBinary ? $code : $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $isBinary ? trim($decrypted) : utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata)
{
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
?>
To directly answer your question: you can simply generate a random IV and prefix it to the ciphertext. You need to do this before encoding the ciphertext to hexadecimals. Then during decryption first decode, then "remove" the IV bytes, initialize the IV and finally decrypt the ciphertext to obtain the plaintext.
Note that the IV will always be 16 bytes for AES in CBC mode, so there is no direct need to include the IV length anywhere. I used quotes around "remove" as both IvParameterSpec as Cipher.doFinal accept buffers with offset and length; there is no need to copy the bytes to different arrays.
Notes:
keys should not be strings; lookup PBKDF's such as PBKDF2 to derive a key from a password or pass phrase;
CBC is generally vulnerable to padding oracle attacks; however, by keeping to PHP's zero padding you may have avoided attacks by accident;
CBC doesn't provide integrity protection, so note that adversaries may change the ciphertext without decryption failing;
if the underlying code that uses the text generates errors then you may be vulnerable to plaintext oracle attacks (padding oracle attacks are only part of the larger group of plaintext oracles);
your Java code is unbalanced; the encrypt and decrypt mode should either perform hex encoding / decoding or they should not;
the exception handling is of course not good (although that may be just for the example);
String#getBytes() will use UTF-8 on Android, but it may use Windows-1252 on Java SE on Windows, so this is prone to generating the wrong key if you're not careful - always define the character set to use.
To use a shared secret to communicate, try TLS in pre-shared secret mode, defined by one of the PSK_ cipher suites.

3DES encryption in iPhone app always produces different result from 3DES encryption in Java

I have to encrypt a string in my iPhone app. The encryption scheme is 3DES/CBC/PKCS5 padding and I have to convert in objective-c this Java code:
public class MessageEncrypt {
public String encryptString(String message, String seckey) throws Exception{
byte[] encData = encrypt(message, seckey);
return this.getHexString(encData, "");
}
public String decryptString(String message, String seckey) throws Exception{
return decrypt(this.getBArray(message), seckey);
}
private byte[] encrypt(String message, String seckey) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(seckey.getBytes("utf-8"));
final byte[] keyBytes = acopyof(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
private String decrypt(byte[] message, String seckey) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(seckey.getBytes("utf-8"));
final byte[] keyBytes = acopyof(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
private String getHexString(byte[] barray, String delim) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < barray.length; i++) {
int ii = barray[i] & 0xFF;
String bInt = Integer.toHexString(ii);
if (ii < 16) {
bInt = "0" + bInt.toUpperCase();
}
buffer.append(bInt);
if (i < barray.length - 1) {
buffer.append(delim);
}
}
return buffer.toString().toUpperCase();
}
private byte[] getBArray(String bString) {
byte[] retBytes;
if (bString.length() % 2 != 0) {
return new byte[0];
}
retBytes = new byte[bString.length() / 2];
for (int i = 0; i < bString.length() / 2; i++) {
retBytes[i] = (byte) ((Character.digit(bString.charAt(2 * i), 16) << 4) + Character.digit(bString.charAt(2 * i + 1), 16));
}
return retBytes;
}
public static byte[] acopyof(byte[] orig, int newlength){
byte[] copya = new byte[newlength];
for(int i=0;i< orig.length;i++){
copya[i]=orig[i];
}
for(int i=orig.length;i<newlength;i++){
copya[i]=0x0;
}
return copya;
}
}
I made this objective-c method to match those specs:
+(NSString*)doCipher:(NSString*)sTextIn:(CCOperation)encryptOrDecrypt {
// const void *vplainText;
// size_t plainTextBufferSize;
NSMutableData *dTextIn;
if (encryptOrDecrypt == kCCDecrypt)
{
}
else
{
dTextIn = [[sTextIn dataUsingEncoding: NSASCIIStringEncoding]mutableCopy];
}
NSLog(#"************** Init encrypting **********************************");
NSLog(#"This is data to encrypt %#",dTextIn);
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t ivkCCBlockSize3DES;
bufferPtrSize = ([dTextIn length] + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x00, bufferPtrSize);
// Initialization vector; in this case 8 bytes.
uint8_t iv[kCCBlockSize3DES];
memset((void *) iv, 0x8, (size_t) sizeof(iv));
UserAndPassword *userPass = [[UserAndPassword alloc]init];
NSString *userPassword = userPass.password;
NSLog(#"This is my password %#",userPassword);
NSString *key = [userPassword MD5String];
NSLog(#"This is MD5 key %#",key);
NSMutableData *_keyData = [[key dataUsingEncoding:NSASCIIStringEncoding]mutableCopy];
unsigned char *bytePtr = (unsigned char *)[_keyData bytes];
NSLog(#"Bytes of key are %s ", bytePtr);
NSLog(#"******** This is my key length %d *******",[_keyData length]);
[_keyData setLength:24];
unsigned char *bytePtr1 = (unsigned char *)[_keyData bytes];
NSLog(#"******** Bytes of key are %s ************", bytePtr1);
NSLog(#"********* This is key length %d ***********",[_keyData length]);
ccStatus = CCCrypt(encryptOrDecrypt, // CCoperation op
kCCAlgorithm3DES, // CCAlgorithm alg
kCCOptionPKCS7Padding, // CCOptions
[_keyData bytes], // const void *key
kCCKeySize3DES, // 3DES key size length 24 bit
iv, //const void *iv,
[dTextIn bytes], // const void *dataIn
[dTextIn length], // size_t dataInLength
(void *)bufferPtr, // void *dataOut
bufferPtrSize, // size_t dataOutAvailable
&movedBytes); // size_t *dataOutMoved
if (ccStatus == kCCParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED";
NSString *result;
if (encryptOrDecrypt == kCCDecrypt)
{
// result = [[NSString alloc] initWithData: [NSData dataWithBytes:(const void *)bufferPtr length:[(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding]];
result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding] autorelease];
}
else
{
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSLog(#"This is my encrypted bytes %#", myData);
result = [NSString dataToHex:myData];
NSLog(#"This is my encrypted string %#", result);
NSLog(#"********************** Encryption is finished ************");
}
return result;
}
I didn't manage to match the 3DES encryption obtained with Java code and I don't understand which is the problem.
Thank you in advance,
Pier
The Java version is using an IV of 0s, while the Objective-C version uses 8s.
Deriving a key from a password using one round of MD5 and no salt is not secure. Use a key derivation algorithm like PBKDF2.
I haven't looked through all your code, but the first thing that jumps out is that the character encoding schemes for your input strings are different. In your Java algorithm you are encoding all strings as UTF-8, but in your ObjC algorithm you encoded the strings as ASCII, which is a potential problem for anything but the simplest of input strings.
It looks like you have a character encoding problem. Your Objective-C code is based on ASCII (8 bit) characters but you need to switch (16 bit) UNICODE character decoding while parsing Java Strings into bytes. On the other hand, It may be a good idea to consider byte ordering in your arrays depending on the CPU architecture you are working on (Little or Big Endianness).

Categories