android - 图像加解密

标签 android

我想加密和解密图像,

该 Activity 将有两个用于加密和解密的按钮

主要 Activity 是

    ctx = this;

     btn_Dec = (Button)findViewById(R.id.btn_Dec);
            btn_In = (Button)findViewById(R.id.btn_In);
            btn_Dec.setOnClickListener(btnDecListner);
            btn_In.setOnClickListener(btnInListner);

        }


        public OnClickListener btnInListner = new OnClickListener() {

            public void onClick(View v) {
                CryptClass simpleCrypto = new CryptClass();
                 System.out.println("Start Encrypting");
                try {
                    // encrypt audio file send as second argument and corresponding key in first argument.
                      incrept = simpleCrypto.encrypt(KEY, getImageFile());

                      //Store encrypted file in SD card of your mobile with name vincent.mp3.
                    FileOutputStream fos = new FileOutputStream(new File("/sdcard/abc.jpg"));
                       fos.write(incrept);
                       fos.close();

                } catch (Exception e) {  
                    e.printStackTrace();
                }
            }
        };


           public OnClickListener btnDecListner = new OnClickListener() {

                public void onClick(View v) {
                    CryptClass simpleCrypto = new CryptClass();

                    try {

                        // decrypt the file here first argument is key and second is encrypted file which we get from SD card.
                        decrpt = simpleCrypto.decrypt(KEY, getImageFileFromSdCard());

                        //play decrypted audio file.
                        ///playMp3(decrpt);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } 
            };

            /**
             * 
             * @return byte array for encryption.
             * @throws FileNotFoundException
             */

        public byte[]   getImageFile() throws FileNotFoundException
            {
              byte[] Image_data = null;
              byte[] inarry = null;

               AssetManager am = ctx.getAssets();
                try {
                    InputStream is = am.open("abc.jpg "); // use recorded file instead of getting file from assets folder.
                    int length = is.available();
                    Image_data = new byte[length];

                    int bytesRead;
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    while ((bytesRead = is.read(Image_data)) != -1)
                    {
                        output.write(Image_data, 0, bytesRead);
                    }
                  inarry = output.toByteArray();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            return inarry;
            }

        /**
         * This method fetch encrypted file which is save in sd card and convert it in byte array after that this  file will be decrept.
         * @return byte array of encrypted data for decription.
         * @throws FileNotFoundException
         */
        public byte[]   getImageFileFromSdCard() throws FileNotFoundException
        {

          byte[] inarry = null;

            try {
                //getting root path where encrypted file is stored.
                File sdcard  = Environment.getExternalStorageDirectory();
                File file = new File(sdcard,"abc.jpg"); //Creating file object

                //Convert file into array of bytes.
                FileInputStream fileInputStream=null;
                byte[] bFile = new byte[(int) file.length()]; 
                fileInputStream = new FileInputStream(file);
                fileInputStream.read(bFile);
                fileInputStream.close();
                inarry = bFile;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return inarry;
        }

还有另一个类执行 key 生成、加密、解密和所有这些操作的操作......
public  byte[] encrypt(String seed, byte[] cleartext) throws Exception {

    byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext);
      //  return toHex(result);
        return result;
}

public  byte[] decrypt(String seed, byte[] encrypted) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = encrypted;
        byte[] result = decrypt(rawKey, enc);

        return result;
}

//done
private  byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
    kgen.init(128, sr); 
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
} 


private  byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
}

private  byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
}

它显示在 Assets 中找不到文件的错误...我已经将 abc.jpg 文件放在 Assets 文件夹中

最佳答案

以下行中有一个额外的空白,

am.open("abc.jpg ");

关于android - 图像加解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14154096/

相关文章:

Android:无法通过 HTTPS 访问本地网站

java - Android Palette 仅适用于某些 RecyclerView 项目

android - 如何增加 RecyclerView 上当前焦点项目的大小?

javascript - 如何用angular2和typescript隐藏android actionbar?

java - Android 应用程序在登录和注册时崩溃

java - 什么时候使用GSON解析对象?

android - 尝试在空对象上调用接口(interface)方法 'android.media.session.ISessionController android.media.session.ISession.getController()'

java - Okhttp3在请求加载之前关闭 Activity 使应用程序崩溃

android - 在手机上测试 Android Wear 应用程序?

android -/data/anr/traces.txt 在程序中不可访问,因为 Android N