pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

解密圖像時(shí),給出 javax.crypto.BadPaddingException: pa

When Decrypting Image, gives javax.crypto.BadPaddingException: pad block corrupted Android(解密圖像時(shí),給出 javax.crypto.BadPaddingException: pad block損壞的Android)
本文介紹了解密圖像時(shí),給出 javax.crypto.BadPaddingException: pad block損壞的Android的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

您好,我是 android 和圖像加密的新手.我的場(chǎng)景是這樣的,

Hi i'm new to android and Image encryption. My scenario is like this,

  • 首先我要加密圖像文件.
  • 那我上傳到服務(wù)器
  • 我正在從我的應(yīng)用下載加密圖像并將其保存在 SD 卡中.
  • 然后我在將其設(shè)置為 imageView 之前對(duì)其進(jìn)行解密

(我用過的所有需要??方法見底部..)

(See bottom for all need methods I have used..)

但我得到 javax.crypto.BadPaddingException: 解密時(shí)墊塊損壞.我讀了一些關(guān)于這個(gè)例外的文章,但都是關(guān)于文本加密的.你能幫我避免這種情況嗎?提前謝謝你

圖像加密使用 ...

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

這里我也保存了其他幾張圖片,都成功保存到了sd卡中...

Here I'm saving several other images as well, all saved in sd card successfully...

for (int i = 0; i < imageUrls.size(); i++)
                {
                    File file = new File(imageUrls.get(i));

                    String metapath = CommonUtils.getDataFromPreferences("metaPath", "");
                    Log.d("metapath", metapath);
                    String extStorageDirectory = metapath + file.getName();

                    File wallpaperDirectory = new File(extStorageDirectory);
                    if (!wallpaperDirectory.exists() || wallpaperDirectory.length() == 0)
                    {
                        new DownloadImagesTask()
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageUrls.get(i));
                    }
                }
                Toast toast = Toast.makeText(ScratchDetailsActivity.this, "Lottery was purchased and saved to sdcard/E-Lottery",
                    Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();

圖像解密...

這里的解密文件第一個(gè)參數(shù)是密鑰,第二個(gè)是我們從 SD 卡獲取的加密文件.

decrypt the file here first argument is key and second is encrypted file which we get from SD card.

        decrpt = simpleCrypto.decrypt(KEY, getImageFileFromSdCard());
        bmpimg2 = BitmapFactory.decodeByteArray(decrpt, 0, decrpt.length);
        Drawable d = new BitmapDrawable(getResources(), bmpimg2);
        hiddenImage.setImageDrawable(d);

下載圖像任務(wù)..

public class DownloadImagesTask extends AsyncTask<String, Void, InputStream>{
private String fileName;

@Override
protected InputStream doInBackground(String... urls)
{
    //Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    return download_Image(urls[0]);
}

@Override
protected void onPostExecute(InputStream result)
{
    storeImage(result);

}

private InputStream download_Image(String url)
{
    InputStream is = null;
    File file = new File(url);
    fileName = file.getName();
    try
    {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        is = conn.getInputStream();
    }
    catch (OutOfMemoryError e)
    {
        Log.e("Hub", "Error getting the image from server : " + e.getMessage().toString());
    }
    catch (IOException e)
    {
        Log.e("Hub", "Error getting the image from server : " + e.getMessage().toString());
    }

    return is;
}

public void storeImage(InputStream is)
{

    String extStorageDirectory = CommonUtils.getDataFromPreferences("metaPath", "");

    Log.d("extStorageDirectory", extStorageDirectory);
    OutputStream outStream = null;

    File wallpaperDirectory = new File(extStorageDirectory);
    if (!wallpaperDirectory.exists())
    {
        wallpaperDirectory.mkdirs();
    }
    File outputFile = new File(wallpaperDirectory, fileName);
    if (!outputFile.exists() || outputFile.length() == 0)
    {
        try
        {
            outStream = new FileOutputStream(outputFile);
        }
        catch (FileNotFoundException e1)
        {
            e1.printStackTrace();
        }

        try
        {
            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = is.read(buffer)) != -1)
            {
                outStream.write(buffer, 0, bytesRead);
            }

            outStream.close();
            is.close();
            Log.d("ScratchActivtiy", "Image Saved");

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

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

getImageFileFromSDCard 方法

getImageFileFromSDCard method

/**
     * 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
    {
        String metapath = CommonUtils.getDataFromPreferences("metaPath", "");

        File imageFolder = new File(metapath);
        File urlFile = new File(selectedLottery.getImage());

        for (File f : imageFolder.listFiles())
        {
            if (urlFile.getName().equals(f.getName()))
                metapath = metapath + f.getName();
        }
        File imageFile = new File(metapath);
        //Convert file into array of bytes.
        FileInputStream fileInputStream = null;
        byte[] bFile = new byte[(int) imageFile.length()];
        fileInputStream = new FileInputStream(imageFile);
        fileInputStream.read(bFile);
        fileInputStream.close();
        inarry = bFile;

    }
    catch (IOException e)
    {
        Log.d("Exception", e.getMessage());
    }

    return inarry;
}

推薦答案

有很多事情可能會(huì)導(dǎo)致 Bad Padding 異常.要檢查的明顯事項(xiàng)是您正在使用的加密和解密:

There are a lot of things that might cause a Bad Padding exception. Obvious things to check are that for both encryption and decryption you are using:

  1. 相同的key,即逐字節(jié)相同.

  1. the same key, that is byte-for-byte the same.

相同的加密模式(通常是 CBC、CTR 或 GCM).

the same encryption mode (CBC, CTR or GCM usually).

相同的 IV/Nonce,再次逐字節(jié)相同.

the same IV/Nonce, again byte-for-byte the same.

相同的填充(PKCS5 或 PKCS7 很常見).

the same padding (PKCS5 or PKCS7 are common).

不要依賴系統(tǒng)默認(rèn)值,尤其是在一個(gè)系統(tǒng)上加密并在另一個(gè)系統(tǒng)上解密時(shí),就像您似乎正在做的那樣.如果系統(tǒng)默認(rèn)值不同,那么您的解密將失敗.始終明確設(shè)置鍵、模式、IV 和填充.在任何合理的加密庫中都會(huì)有記錄的方法.

Do not rely on system defaults, especially when encrypting on one system and decrypting on another, as you seem to be doing. If the system defaults are different, then your decryption will fail. Always explicitly set key, mode, IV and padding. There will be documented ways to do so in any reasonable crypto library.

如果這不能解決問題,那么您將需要做更多的挖掘工作.將解密方法臨時(shí)設(shè)置為 NoPadding 或您的庫使用的任何等效方法.這將使解密方法忽略填充錯(cuò)誤,并為您提供一些輸出.查看輸出并將其與原始輸入進(jìn)行比較;您可能需要查看此處的十六進(jìn)制轉(zhuǎn)儲(chǔ)以確定發(fā)生了什么.

If that doesn't solve it then you will need to do a bit more digging. Set the decryption method temporarily to NoPadding or whatever equivalent your library uses. That will let the decryption method ignore padding errors, and give you some output. Have a look at the output and compare it to the original input; you may have to look at hex dumps here to be sure what is happening.

其中的可能性有:

  1. 輸出完全是垃圾:您的密鑰錯(cuò)誤,或者 IV/Nonce對(duì)于流密碼或 GCM 模式或 CTR 模式是錯(cuò)誤的.

  1. the output is complete garbage: your key is wrong, or the IV/Nonce is wrong for a stream cypher or GCM mode or CTR mode.

第一個(gè)塊是垃圾,其余的與明文匹配:你在 CBC 模式下輸入錯(cuò)誤的 IV.

the first block is garbage with the rest matching the plaintext: you have the wrong IV in CBC mode.

輸出最后匹配了一些額外的東西:額外的東西是填充.將您的解密方法設(shè)置為期望該類型的填充.

the output matches with some extra stuff at the end: the extra stuff is padding. Set your decryption method to expect that type of padding.

如果這些都沒有發(fā)生,請(qǐng)?jiān)诖颂幵俅卧儐柌⒚枋霭Y狀.

If none of these happen, then ask again here, describing the symptoms.

當(dāng)您找到解決方案后,您必須將您的解密方法重新設(shè)置為期望正確的填充.將其設(shè)置為 NoPadding 是不安全的,因?yàn)槿魏闻f垃圾都可以添加到解密的明文中.

When you have got a solution, you must set your decryption method back to expect the correct padding. Leaving it set to NoPadding is not secure since any old garbage can be added to the decrypted plaintext.

這篇關(guān)于解密圖像時(shí),給出 javax.crypto.BadPaddingException: pad block損壞的Android的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Java Remove Duplicates from an Array?(Java從數(shù)組中刪除重復(fù)項(xiàng)?)
How to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修復(fù)調(diào)用失敗來自服務(wù)器的意外響應(yīng):在 Android 工作室中未經(jīng)授權(quán))
AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)
AES Error: Given final block not properly padded(AES 錯(cuò)誤:給定的最終塊未正確填充)
Detecting incorrect key using AES/GCM in JAVA(在 JAVA 中使用 AES/GCM 檢測(cè)不正確的密鑰)
AES-256-CBC in Java(Java 中的 AES-256-CBC)
主站蜘蛛池模板: 热缩管切管机-超声波切带机-织带切带机-无纺布切布机-深圳市宸兴业科技有限公司 | 深圳成考网-深圳成人高考报名网 深圳工程师职称评定条件及流程_深圳职称评审_职称评审-职称网 | 温控器生产厂家-提供温度开关/热保护器定制与批发-惠州市华恺威电子科技有限公司 | 齿轮减速电机一体机_蜗轮蜗杆减速马达-德国BOSERL齿轮减速机带电机生产厂家 | 直流电能表-充电桩电能表-导轨式电能表-智能电能表-浙江科为电气有限公司 | 偏心半球阀-电动偏心半球阀-调流调压阀-旋球阀-上欧阀门有限公司 | 气动|电动调节阀|球阀|蝶阀-自力式调节阀-上海渠工阀门管道工程有限公司 | SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | 成都顶呱呱信息技术有限公司-贷款_个人贷款_银行贷款在线申请 - 成都贷款公司 | 阴离子聚丙烯酰胺价格_PAM_高分子聚丙烯酰胺厂家-河南泰航净水材料有限公司 | 脑钠肽-白介素4|白介素8试剂盒-研域(上海)化学试剂有限公司 | 珠海白蚁防治_珠海灭鼠_珠海杀虫灭鼠_珠海灭蟑螂_珠海酒店消杀_珠海工厂杀虫灭鼠_立净虫控防治服务有限公司 | 合肥展厅设计-安徽展台设计-合肥展览公司-安徽奥美展览工程有限公司 | 课件导航网_ppt课件_课件模板_课件下载_最新课件资源分享发布平台 | 火锅加盟_四川成都火锅店加盟_中国火锅连锁品牌十强_朝天门火锅【官网】 | 齿轮减速机_齿轮减速电机-VEMT蜗轮蜗杆减速机马达生产厂家瓦玛特传动瑞环机电 | 云南外加剂,云南速凝剂,云南外加剂代加工-普洱澜湄新材料科技有限公司 | 安徽成考网-安徽成人高考网 | 贴片电容-贴片电阻-二三极管-国巨|三星|风华贴片电容代理商-深圳伟哲电子 | 百度爱采购运营研究社社群-店铺托管-爱采购代运营-良言多米网络公司 | 卫生纸复卷机|抽纸机|卫生纸加工设备|做卫生纸机器|小型卫生纸加工需要什么设备|卫生纸机器设备多少钱一台|许昌恒源纸品机械有限公司 | 多功能三相相位伏安表-变压器短路阻抗测试仪-上海妙定电气 | 低噪声电流前置放大器-SR570电流前置放大器-深圳市嘉士达精密仪器有限公司 | 吊篮式|移动式冷热冲击试验箱-二槽冷热冲击试验箱-广东科宝 | 钢制暖气片散热器_天津钢制暖气片_卡麦罗散热器厂家 | 学校用栓剂模,玻璃瓶轧盖钳,小型安瓿熔封机,实验室安瓿熔封机-长沙中亚制药设备有限公司 | 阀门智能定位器_电液动执行器_气动执行机构-赫尔法流体技术(北京)有限公司 | 火锅底料批发-串串香技术培训[川禾川调官网] | 湖州织里童装_女童男童中大童装_款式多尺码全_织里儿童网【官网】-嘉兴嘉乐网络科技有限公司 | 河南空气能热水器-洛阳空气能采暖-洛阳太阳能热水工程-洛阳润达高科空气能商行 | 万师讲师网-优质讲师培训师供应商,讲师认证,找讲师来万师 | 美甲贴片-指甲贴片-穿戴美甲-假指甲厂家--薇丝黛拉 | 泰国试管婴儿_泰国第三代试管婴儿_泰国试管婴儿费用/多少钱_孕泰来 | atcc网站,sigma试剂价格,肿瘤细胞现货,人结肠癌细胞株购买-南京科佰生物 | 山东钢格板|栅格板生产厂家供应商-日照森亿钢格板有限公司 | 粘度计维修,在线粘度计,二手博勒飞粘度计维修|收购-天津市祥睿科技有限公司 | 危废处理系统,水泥厂DCS集散控制系统,石灰窑设备自动化控制系统-淄博正展工控设备 | 杰福伦_磁致伸缩位移传感器_线性位移传感器-意大利GEFRAN杰福伦-河南赉威液压科技有限公司 | 药品冷藏箱厂家_低温冰箱_洁净工作台-济南欧莱博电子商务有限公司官网 | 工业废水处理|污水处理厂|废水治理设备工程技术公司-苏州瑞美迪 今日娱乐圈——影视剧集_八卦娱乐_明星八卦_最新娱乐八卦新闻 | 外贮压-柜式-悬挂式-七氟丙烷-灭火器-灭火系统-药剂-价格-厂家-IG541-混合气体-贮压-非贮压-超细干粉-自动-灭火装置-气体灭火设备-探火管灭火厂家-东莞汇建消防科技有限公司 |