黑莓中的AES解密

时间:2012-01-04 18:05:11

标签: java blackberry encryption

我有一个显示从服务器下载的图像的应用程序。图像已加密并使用AES保存在服务器中。我需要在客户端解密图像。用于加密的代码如下

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

我无法使用Blackberry AESDecryptor Engine对此进行解密。我是这个加密图形的新手。是否可以使用AESDecryptor引擎进行解密。我附上了我正在使用的代码。请帮我解决这个问题

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

2 个答案:

答案 0 :(得分:1)

你没有真正说出你的问题是什么,但至少以下一行看起来不正确:

BlockDecryptor decryptor = new BlockDecryptor(engine, input);

应该是

BlockDecryptor decryptor = new BlockDecryptor(uengine, input);

我刚刚将engine更改为uengine

答案 1 :(得分:0)

RIM的API使这很容易,但找到文档有点困难。查看软件包net.rim.device.api.crypto的Javadocs:

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

您应该查看所有内容,但答案在第7位:加密器和解密器工厂。

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

DecryptorFactory可以创建一个输入流,您可以像任何InputStream一样读取它。