user1111471
user1111471

Reputation: 11

AESDecryption in Blackberry

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();
    }

Upvotes: 1

Views: 825

Answers (2)

Kurt Zettel
Kurt Zettel

Reputation: 54

RIM's APIs make this pretty easy but it is a little tough to find the documentation. Check out the Javadocs for the package net.rim.device.api.crypto at:

http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/crypto/package-summary.html

You should look through all of it but the answer is in number 7: Encryptor and decryptor factories.

http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/crypto/doc-files/factories.html

The DecryptorFactory can create an input stream that you can just read as any InputStream.

Upvotes: 0

President James K. Polk
President James K. Polk

Reputation: 42009

You don't really say what your problem is, but at least the following line looks incorrect:

BlockDecryptor decryptor = new BlockDecryptor(engine, input);

It should be

BlockDecryptor decryptor = new BlockDecryptor(uengine, input);

I just changed engine to uengine

Upvotes: 1

Related Questions