0

i m writing one application which encrypt and decrypt data using AES (ECB) mode. Encrypted data of blackberry code successfully decrypt by php code. but problem is that when i get encrypted text from php i m not able to decrypt it with blackberry code..even i m not getting any exception.

here is my code to encrypt and decrypt text.

public static  byte[] encrypt( byte[] keyData, byte[] data )
throws CryptoException, IOException
{
    // Create the AES key to use for encrypting the data.
    // This will create an AES key using as much of the keyData
    // as possible.
    AESKey key = new AESKey( keyData );

    // Now, we want to encrypt the data.
    // First, create the encryptor engine that we use for the actual
    // encrypting of the data.
    AESEncryptorEngine engine = new AESEncryptorEngine( key );

    // Since we cannot guarantee that the data will be of an equal block
    // length we want to use a padding engine (PKCS5 in this case).
    PKCS5FormatterEngine fengine = new PKCS5FormatterEngine( engine );

    // Create a BlockEncryptor to hide the engine details away.
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    BlockEncryptor encryptor = new BlockEncryptor( fengine, output );



    encryptor.write( data );

    encryptor.close();
    output.close();


    return output.toByteArray();
}
public static String AESDecryption(byte[] keyData,byte[] cipherText, int dataLength ) throws CryptoException, IOException {

    // Create the input stream based on the ciphertext
    ByteArrayInputStream in = new ByteArrayInputStream( cipherText, 0, dataLength );

    // Now create the block decryptor and pass in a new instance
    // of an AES decryptor engine with the specified block length
    BlockDecryptor cryptoStream = new BlockDecryptor(new AESDecryptorEngine( new AESKey( keyData )), in );

    byte[] T= new byte[dataLength];
    // Read the decrypted text from the AES decryptor stream and
    // return the actual length read

    int length= cryptoStream.read( T );
  String str= new String(T);


  return str;
}

thanks in advance..

Nirav Bhandari
  • 4,200
  • 5
  • 29
  • 58

2 Answers2

3

Here is the method that accepts key and encrypted data (in the form of byte arrays) and returns the decrypted data in the form of byte array:

public static byte[] decrypt(byte[] keyData, byte[] ciphertext) 
         throws CryptoException, IOException {

    // First, create the AESKey again.
    AESKey key = new AESKey(keyData);

    // Now, create the decryptor engine.
    AESDecryptorEngine engine = new AESDecryptorEngine(key);
    // Since we cannot guarantee that the data will be of an equal block length
    // we want to use a padding engine (PKCS5 in this case).
    PKCS5UnformatterEngine uengine = new PKCS5UnformatterEngine(engine);

    // Create the BlockDecryptor to hide the decryption details away.
    ByteArrayInputStream input = new ByteArrayInputStream(ciphertext);
    BlockDecryptor decryptor = new BlockDecryptor(uengine, input);

    // Now, read in the data.
    byte[] temp = new byte[100];
    DataBuffer buffer = new DataBuffer();

    for (;;) {
        int bytesRead = decryptor.read(temp);
        buffer.write(temp, 0, bytesRead);

        if (bytesRead < 100) {
            // We ran out of data.
            break;
        }
    }

    byte[] plaintext = buffer.getArray();

    return plaintext;
}

Note encryption/decryption does not operate with strings directly. It only work with byte arrays. So as a final action you need to convert decrypted byte array to string using String(byte[] bytes) or String(byte[] bytes, String enc) constructor. The second constructor can be useful if your string were encoded with any other than "ISO-8859-1" encoding (which is a default one for BlackBerry).

UPDATE:

As it turns out you don't use PKCS5 padding on server side AND you convert encrypted byte data into a HEX string, then the solution code is:

// this is to convert HEX to bytes
public static byte[] convertHexToBytes(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

// this is the same as initial version, but we don't handle PKCS5 padding here
public static byte[] decrypt(byte[] keyData, byte[] ciphertext)
        throws CryptoException, IOException {

    // First, create the AESKey again.
    AESKey key = new AESKey(keyData);

    // Now, create the decryptor engine.
    AESDecryptorEngine engine = new AESDecryptorEngine(key);

    // Create the BlockDecryptor to hide the decryption details away.
    ByteArrayInputStream input = new ByteArrayInputStream(ciphertext);
    BlockDecryptor decryptor = new BlockDecryptor(engine, input);

    // Now, read in the data.
    byte[] temp = new byte[100];
    DataBuffer buffer = new DataBuffer();

    for (;;) {
        int bytesRead = decryptor.read(temp);
        buffer.write(temp, 0, bytesRead);

        if (bytesRead < 100) {
            // We ran out of data.
            break;
        }
    }

    byte[] plaintext = buffer.getArray();

    return plaintext;
}

// and finally :)
String key =       "1234567890123456";
String encrypted = "48b983c4f1575280d244b74cf689efe5";

byte[] keyBytes = key.getBytes();
byte[] encryptedBytes = convertHexToBytes(encrypted);

// displays "nirav bhandari"
Dialog.inform(new String(decrypt(keyBytes, encryptedBytes)));
Vit Khudenko
  • 27,639
  • 10
  • 56
  • 86
  • i have also used the same code you mention above...bt it also worth less...encrypted text from php doesnt get decryptd... here is a representation of my cipher 48b983c4f1575280d244b74cf689efe5 and key is 1234567890123456 try to decrypt it....you wont able to decrypt it my friend.... – Nirav Bhandari Jun 28 '12 at 11:10
  • the main question is what is 48b983c4f1575280d244b74cf689efe5? is it the string you get on BB side? It looks like a HASH.. Or is it a Base64 encoded string? what do you do on php side with encrypted byte array before you send it to BB? – Vit Khudenko Jun 28 '12 at 11:15
  • dude it is hexa code...i m converting it to byte and then decrypt it using above function...but not getting output..even i m not getting invalid plain text...exception also says "No stack trace"..so dont know what is problem..and if i place hexacode othe than 48b983c4f1575280d244b74cf689efe5 then my bb code decrypt it and giving me invalid plain text..so dont know whats d problem is – Nirav Bhandari Jun 28 '12 at 11:28
  • ok, let me try again. :) please explain in detailed steps what do you do with the data starting from the point "encrypted byte array on php side" and before you are about to pass it to `decrypt()` on BB. that's very important. feel free to update the main post, rather than adding a comment. – Vit Khudenko Jun 28 '12 at 11:33
  • here is my phpcode $cypher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); $decrypted = mdecrypt_generic($cypher, hex2bin($data));// base64_decode($data)); // clean up mcrypt_generic_deinit($cypher); mcrypt_module_close($cypher); return utf8_encode(trim($decrypted)); – Nirav Bhandari Jun 28 '12 at 11:43
  • this does not look for me as encryption code.. :) or am I missing anything? – Vit Khudenko Jun 28 '12 at 11:57
  • Sorry man, that's impossible. I'm spending my work time on this, I hope you understand it. Looks like I am not able to help you since you can not explain what excatly you do on server side. – Vit Khudenko Jun 28 '12 at 12:04
  • 1
    on server side..first i m converting data to cypher using rijandl 128 bit AES algo.After that i m converting binary cypher to hexa and returing it to my clienyt. thats it... – Nirav Bhandari Jun 28 '12 at 12:21
  • ok, understood. looks like your problem is on server side. don't you ignore PKCS5Padding on server side? check how to use PKCS5Padding here: http://us3.php.net/manual/en/ref.mcrypt.php#69782. FYI: PHP does not add padding by default. – Vit Khudenko Jun 28 '12 at 12:48
  • ok, I got it, your plain text is "nirav bhandari" :) I'll update my answer ASAP with the code. – Vit Khudenko Jun 28 '12 at 13:47
  • Please check the UPDATE section. BTW, we could spend on this MUCH less time if you provided all the details in your initial question. And also I hope now you should understand why I did not answer you within the first/another question. – Vit Khudenko Jun 28 '12 at 14:00
  • but where to find udate section? – Nirav Bhandari Jun 28 '12 at 14:04
  • ohhh...ok.srry srry...got it// – Nirav Bhandari Jun 28 '12 at 14:04
  • thanks man........code is working .......thanks a lot man...thanks 4 your help..i have spent my whole day to solve this problem...thanks once again.. – Nirav Bhandari Jun 28 '12 at 14:09
  • I'm glad I was helpful and we've finally come to a solution. :) – Vit Khudenko Jun 28 '12 at 14:11
  • yaa..finally we come to solution...people like u become helping hand for us..thanks a lot man... – Nirav Bhandari Jun 28 '12 at 14:20
  • hey man...cn u solve this problem http://stackoverflow.com/questions/11483128/custom-list-field-click-event – Nirav Bhandari Jul 14 '12 at 10:51
1

When you call decryption function, How you convert cipher text into Byte[]?

  • I am asking Nirav Bhandari "what do you do on php side with encrypted byte array before you send it to BB?", but still we are not on the same page.. :) – Vit Khudenko Jun 28 '12 at 12:18
  • on server side..i m performing followingoperatio on plain text first i m converting plain text to cypher using rijandl 128 bit AES algo....using following code $cypher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); then i m encrypting data using default php function $encrypted = mcrypt_generic($cypher,$data);// ( mdecrypt_generic($cypher, $data); then converting it to hexa and returning.. After that i m converting binary cypher to hexa and returing it to my clienyt. thats it.. – Nirav Bhandari Jun 28 '12 at 12:31