Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
colombus
Posts: 264
Registered: ‎06-04-2009
My Device: Not Specified

AES decryption

Hi 

I have an application which displays image downloaded from server. the image is encrypted and kept in the server using AES. I need to decrypt the image at the client side. The code used for encryption is as follows

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;

public class Crypto {
    Cipher ecipher;
    Cipher dcipher;

    /**
    * Input a string that will be md5 hashed to create the key.
    * @return void, cipher initialized
    */

    public Crypto(){
        try{
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            this.setupCrypto(kgen.generateKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public Crypto(String key){
        SecretKeySpec skey = new SecretKeySpec(getMD5(key), "AES");
        this.setupCrypto(skey);
    }

    private void setupCrypto(SecretKey key){
        try
        {    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            ecipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
            dcipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

            ecipher.init(Cipher.ENCRYPT_MODE, key);
            dcipher.init(Cipher.DECRYPT_MODE, key);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    // Buffer used to transport the bytes from one stream to another
    byte[] buf = new byte[1024];

    public void encrypt(InputStream in, OutputStream out){
        try {
            // Bytes written to out will be encrypted
            out = new CipherOutputStream(out, ecipher);

            // Read in the cleartext bytes and write to out to encrypt
            int numRead = 0;
            while ((numRead = in.read(buf)) >= 0){
                out.write(buf, 0, numRead);
            }
            out.close();
        }
        catch (java.io.IOException e){
            e.printStackTrace();
        }
    }


    public void decrypt(InputStream in, OutputStream out){
    	
        try {
            // Bytes read from in will be decrypted
            in = new CipherInputStream(in, dcipher);

            // Read in the decrypted bytes and write the cleartext to out
            int numRead = 0;
            while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead);
            }
            out.close();
        } catch (java.io.IOException e) {
             e.printStackTrace();
        }
    }

    private static byte[] getMD5(String input){
        try{
            byte[] bytesOfMessage = input.getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            return md.digest(bytesOfMessage);
        }  catch (Exception e){
             return null;
        }
    }


    public static void main(String args[]){
        try {
               
           
            Crypto encrypter = new Crypto("yursxjdlbkuikeqe");  ///key for decryption logic
             encrypter.encrypt(new FileInputStream("D:\\Path\\Lighthouse.jpg"),new FileOutputStream("D:\\Encryption\\iOS code base\\Lighthouse.jpg.pkcs5"));
               encrypter.decrypt(new FileInputStream("D:\\Path\\Lighthouse.jpg.pkcs5"),new FileOutputStream("D:\\Encryption\\iOS code base\\Lighthouse.jpg"));
             System.out.println("DONE");
       }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 I am not able to decrypt this using Blackberry AESDecryptor Engine. I am new to this crypto graphy. Is it possible to decrypt using AESDecryptor engine. I am attaching the code which I am using. Please help me in solving this

 

public MyScreen(){       
		// Set the displayed title of the screen       
		setTitle("MyTitle");
		
		byte[] keyData = new String("yursxjdlbkuikeqe").getBytes();
		byte[] cipherText = openFile("file:///SDCard/Lighthouse.jpg.pkcs5");
		try {
			imageData = decrypt(keyData, cipherText);
		} catch (CryptoException e) {
			System.out.println("::::::::::::::::::::::::::::::::::Crypto Exception:::::::"+e.getMessage());
		} catch (IOException e) {
			System.out.println("::::::::::::::::::::::::::::::::::IO Exception:::::::"+e.getMessage());
		}
		if(imageData!=null){
			writeByteData(imageData);
//			EncodedImage image = EncodedImage.createEncodedImage(imageData, 0, imageData.length);
//			add(new BitmapField(image.getBitmap()));
			System.out.println("------------------Image saved successfully-----------");
		}else{
			System.out.println("-------------------Image Data is null");
		}
	}

public static byte[] decrypt(byte[] keyData, byte[] ciphertext) throws CryptoException, IOException {
		// First, create the AESKey again.
		/*String str=new String(keyData);
        System.out.println(str);*/
		
		AESKey key = new AESKey(keyData,0,128);
		System.out.println("Key is ::"+key.getAlgorithm()+"Length:"+key.getBitLength());
//
//		// Now, create the decryptor engine.
		AESDecryptorEngine engine = new AESDecryptorEngine(key);
		PKCS5UnformatterEngine uengine = new PKCS5UnformatterEngine(engine);
/
//		// Create the BlockDecryptor to hide the decryption details away.
		ByteArrayInputStream input = new ByteArrayInputStream(ciphertext);
		BlockDecryptor decryptor = new BlockDecryptor(engine, input);
		byte[] plaintextAndHash = new byte[1024];
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		int bytesRead=0;
		do{
			bytesRead =decryptor.read(plaintextAndHash);
			if(bytesRead!=-1){
				output.write(plaintextAndHash,0,bytesRead);
			}
			
		}
		while(bytesRead!=-1);
		

		return output.toByteArray();
	}

 

Please use plain text.
Developer
colombus
Posts: 264
Registered: ‎06-04-2009
My Device: Not Specified

Re: AES decryption

Any Ideas on this ?? Can USe BlocKDecryptor to decrypt this image ?? Am I missing something. Please help

Please use plain text.
Developer
peter_strange
Posts: 19,608
Registered: ‎07-14-2008
My Device: Not Specified

Re: AES decryption

I have exchanged encrypted data with a number of host systems.  In every case, there has been some subtle difference in the way that the platforms were processing, and the only way to resolve these was to effectively step through each phase of the processing and make sure the results were the same. 

 

You need to start by making 100% sure that the data you are processing is the same as the data the Server has sent.  It could be translated into characters or some other processing in the passage from the Server to the Blackberry. 

 

You can start by making sure your encryption can be 'round tripped, in other words you can decrypt and then encrypt back to the original encrypted data.  if you can't do that there is presumably some difference in the way you are processing on the Blackberry.

 

Assuming that works, and that round tripping on the Server works also, then you are going to have to delve into the actual encryption.  I recommend that to do this you start with a 16 byte character data, encrypt it on the Server, encrypt it on the Blackberry and make sure you get the same result.  Then try decrypting on the BlackBerry.  The advantage of using 16 bytes text is that there is no translation involved, no padding involved and no block chaining involved.  You will need some mechanism to print off the actual byte data so you can compare in detail.

 

Anyway, that is what I would do and I have had to do in a number of cases to understand where the problem is.  Usually it is something silly, like giving a key of 1234567812345678, and one end treating this as ASCII the other as hexadecimal. 

 

Good luck.

Please use plain text.