Android 加密/解密问题 (AES)

Posted

技术标签:

【中文标题】Android 加密/解密问题 (AES)【英文标题】:Android encryption/decryption issue (AES) 【发布时间】:2011-07-25 07:56:18 【问题描述】:

我在这里需要一点帮助。所以基本上我必须在 android 中对图像的 AES 加密/解密进行测试。我是 android 编程的新手,这就是为什么我的一个朋友给我一个例子来说明如何这样做,但问题是,当我运行示例时,它会在 20-30 秒后崩溃,我不确定发生了什么。所以任何人都可以查看代码并告诉我问题出在哪里。示例代码需要这样做:加密和解密同一个图像,并显示一个包含信息的日志,加密和解密图像需要多长时间。无论如何,谢谢!

代码:

    package com.cryptooo.lol;

import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

public class SimpleCryptoActivity extends Activity 

    @Override
    public void onCreate(Bundle savedInstanceState)
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        new Thread() 
            public void run()
                Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shit);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object   
                byte[] b = baos.toByteArray();  

                try 
                byte[] keyStart = "MARTIN_123_MARTIN_123".getBytes();
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
                sr.setSeed(keyStart);
                kgen.init(128, sr); // 192 and 256 bits may not be available
                SecretKey skey = kgen.generateKey();
                byte[] key = skey.getEncoded();    

                // encrypt
                byte[] encryptedData = encrypt(key,b);
                // decrypt
                long start = System.currentTimeMillis()/1000L;
                byte[] decryptedData = decrypt(key,encryptedData);
                long end = System.currentTimeMillis()/1000L;
                android.util.Log.d("TEST","Time "+ String.valueOf(end-start));
                
                catch(Exception e)
                    e.fillInStackTrace();
                
            

            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;
            
        .start(); 
     


这里是 LogCat:

07-25 09:53:01.243: DEBUG/AndroidRuntime(624): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
07-25 09:53:01.253: DEBUG/AndroidRuntime(624): CheckJNI is ON
07-25 09:53:01.463: DEBUG/AndroidRuntime(624): --- registering native functions ---
07-25 09:53:01.843: DEBUG/ddm-heap(624): Got feature list request
07-25 09:53:02.234: DEBUG/PackageParser(52): Scanning package: /data/app/vmdl26130.tmp
07-25 09:53:02.364: INFO/PackageManager(52): Removing non-system package:com.cryptooo.lol
07-25 09:53:02.373: DEBUG/PackageManager(52): Removing package com.cryptooo.lol
07-25 09:53:02.373: DEBUG/PackageManager(52):   Activities: com.cryptooo.lol.SimpleCryptoActivity
07-25 09:53:02.464: DEBUG/PackageManager(52): Scanning package com.cryptooo.lol
07-25 09:53:02.464: INFO/PackageManager(52): /data/app/vmdl26130.tmp changed; unpacking
07-25 09:53:02.484: DEBUG/installd(32): DexInv: --- BEGIN '/data/app/vmdl26130.tmp' ---
07-25 09:53:02.713: DEBUG/dalvikvm(630): DexOpt: load 44ms, verify 27ms, opt 1ms
07-25 09:53:02.723: DEBUG/installd(32): DexInv: --- END '/data/app/vmdl26130.tmp' (success) ---
07-25 09:53:02.723: DEBUG/PackageManager(52):   Activities: com.cryptooo.lol.SimpleCryptoActivity
07-25 09:53:02.745: DEBUG/ActivityManager(52): Uninstalling process com.cryptooo.lol
07-25 09:53:02.833: INFO/installd(32): move /data/dalvik-cache/data@app@vmdl26130.tmp@classes.dex -> /data/dalvik-cache/data@app@com.cryptooo.lol.apk@classes.dex
07-25 09:53:02.843: DEBUG/PackageManager(52): New package installed in /data/app/com.cryptooo.lol.apk
07-25 09:53:02.973: DEBUG/AndroidRuntime(624): Shutting down VM
07-25 09:53:02.973: DEBUG/dalvikvm(624): DestroyJavaVM waiting for non-daemon threads to exit
07-25 09:53:02.985: DEBUG/dalvikvm(624): DestroyJavaVM shutting VM down
07-25 09:53:02.985: DEBUG/dalvikvm(624): HeapWorker thread shutting down
07-25 09:53:02.985: DEBUG/dalvikvm(624): HeapWorker thread has shut down
07-25 09:53:02.985: DEBUG/jdwp(624): JDWP shutting down net...
07-25 09:53:02.985: INFO/dalvikvm(624): Debugger has detached; object registry had 1 entries
07-25 09:53:02.985: DEBUG/dalvikvm(624): VM cleaning up
07-25 09:53:03.004: DEBUG/ActivityManager(52): Uninstalling process com.cryptooo.lol
07-25 09:53:03.024: DEBUG/dalvikvm(624): LinearAlloc 0x0 used 623916 of 5242880 (11%)
07-25 09:53:03.024: ERROR/AndroidRuntime(624): ERROR: thread attach failed
07-25 09:53:03.223: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f0700e5
07-25 09:53:03.235: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f020031
07-25 09:53:03.235: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f020030
07-25 09:53:03.235: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f050000
07-25 09:53:03.284: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f060000
07-25 09:53:03.284: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f060001
07-25 09:53:03.473: DEBUG/dalvikvm(98): GC freed 149 objects / 7384 bytes in 244ms
07-25 09:53:03.583: WARN/dalvikvm(52): threadid=15: spin on suspend #0 threadid=21 (h=1324960)
07-25 09:53:03.593: WARN/dalvikvm(52): dumping state: process - 52
07-25 09:53:03.593: INFO/dalvikvm(52): "android.server.ServerThread" prio=5 tid=15 RUNNABLE
07-25 09:53:03.593: INFO/dalvikvm(52):   | group="main" sCount=0 dsCount=0 s=N obj=0x44c017e0 self=0x147d30
07-25 09:53:03.593: INFO/dalvikvm(52):   | sysTid=61 nice=-2 sched=0/0 cgrp=default handle=1306264
07-25 09:53:03.593: INFO/dalvikvm(52):   at java.lang.Runtime.gc(Native Method)
07-25 09:53:03.593: INFO/dalvikvm(52):   at com.android.internal.os.BinderInternal.forceGc(BinderInternal.java:83)
07-25 09:53:03.593: INFO/dalvikvm(52):   at android.app.ActivityThread.doGcIfNeeded(ActivityThread.java:2296)
07-25 09:53:03.593: INFO/dalvikvm(52):   at android.app.ActivityThread$GcIdler.queueIdle(ActivityThread.java:2010)
07-25 09:53:03.593: INFO/dalvikvm(52):   at android.os.MessageQueue.next(MessageQueue.java:116)
07-25 09:53:03.593: INFO/dalvikvm(52):   at android.os.Looper.loop(Looper.java:110)
07-25 09:53:03.593: INFO/dalvikvm(52):   at com.android.server.ServerThread.run(SystemServer.java:428)
07-25 09:53:03.605: INFO/dalvikvm(52): "PackageManager" prio=5 tid=21 RUNNABLE
07-25 09:53:03.605: INFO/dalvikvm(52):   | group="main" sCount=1 dsCount=0 s=N obj=0x44c37b10 self=0x11fb40
07-25 09:53:03.605: INFO/dalvikvm(52):   | sysTid=67 nice=10 sched=0/0 cgrp=bg_non_interactive handle=1324960
07-25 09:53:03.695: INFO/dalvikvm(52):   at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:~12017)
07-25 09:53:03.695: INFO/dalvikvm(52):   at com.android.server.PackageManagerService.sendPackageBroadcast(PackageManagerService.java:3662)
07-25 09:53:03.695: INFO/dalvikvm(52):   at com.android.server.PackageManagerService.access$1400(PackageManagerService.java:109)
07-25 09:53:03.695: INFO/dalvikvm(52):   at com.android.server.PackageManagerService$PackageRemovedInfo.sendBroadcast(PackageManagerService.java:4533)
07-25 09:53:03.695: INFO/dalvikvm(52):   at com.android.server.PackageManagerService$5.run(PackageManagerService.java:3792)
07-25 09:53:03.695: INFO/dalvikvm(52):   at android.os.Handler.handleCallback(Handler.java:587)
07-25 09:53:03.695: INFO/dalvikvm(52):   at android.os.Handler.dispatchMessage(Handler.java:92)
07-25 09:53:03.695: INFO/dalvikvm(52):   at android.os.Looper.loop(Looper.java:123)
07-25 09:53:03.695: INFO/dalvikvm(52):   at android.os.HandlerThread.run(HandlerThread.java:60)
07-25 09:53:03.714: WARN/dalvikvm(52): threadid=15: spin on suspend resolved in 373 msec
07-25 09:53:03.984: DEBUG/dalvikvm(52): GC freed 22016 objects / 1235352 bytes in 643ms
07-25 09:53:04.064: DEBUG/AndroidRuntime(635): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
07-25 09:53:04.083: DEBUG/AndroidRuntime(635): CheckJNI is ON
07-25 09:53:04.404: DEBUG/AndroidRuntime(635): --- registering native functions ---
07-25 09:53:04.905: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f0700e5
07-25 09:53:04.905: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f020031
07-25 09:53:04.905: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f020030
07-25 09:53:04.905: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f050000
07-25 09:53:05.013: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f060000
07-25 09:53:05.034: WARN/ResourceType(52): Resources don't contain package for resource number 0x7f060001
07-25 09:53:05.064: DEBUG/ddm-heap(635): Got feature list request
07-25 09:53:05.824: DEBUG/dalvikvm(52): GC freed 4805 objects / 259312 bytes in 480ms
07-25 09:53:05.933: DEBUG/ActivityManager(52): Uninstalling process com.cryptooo.lol
07-25 09:53:05.933: INFO/ActivityManager(52): Starting activity: Intent  act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.cryptooo.lol/.SimpleCryptoActivity 
07-25 09:53:05.984: DEBUG/AndroidRuntime(635): Shutting down VM
07-25 09:53:05.984: DEBUG/dalvikvm(635): DestroyJavaVM waiting for non-daemon threads to exit
07-25 09:53:05.993: DEBUG/dalvikvm(635): DestroyJavaVM shutting VM down
07-25 09:53:05.993: DEBUG/dalvikvm(635): HeapWorker thread shutting down
07-25 09:53:06.003: DEBUG/dalvikvm(635): HeapWorker thread has shut down
07-25 09:53:06.003: DEBUG/jdwp(635): JDWP shutting down net...
07-25 09:53:06.003: INFO/dalvikvm(635): Debugger has detached; object registry had 1 entries
07-25 09:53:06.003: DEBUG/dalvikvm(635): VM cleaning up
07-25 09:53:06.043: DEBUG/dalvikvm(635): LinearAlloc 0x0 used 639500 of 5242880 (12%)
07-25 09:53:06.074: ERROR/AndroidRuntime(635): ERROR: thread attach failed
07-25 09:53:06.114: INFO/ActivityManager(52): Start proc com.cryptooo.lol for activity com.cryptooo.lol/.SimpleCryptoActivity: pid=643 uid=10038 gids=
07-25 09:53:06.344: DEBUG/ddm-heap(643): Got feature list request
07-25 09:53:06.484: WARN/ActivityThread(643): Application com.cryptooo.lol is waiting for the debugger on port 8100...
07-25 09:53:06.513: INFO/System.out(643): Sending WAIT chunk
07-25 09:53:06.584: INFO/dalvikvm(643): Debugger is active
07-25 09:53:06.723: INFO/System.out(643): Debugger has connected
07-25 09:53:06.723: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:06.924: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:07.133: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:07.333: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:07.533: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:07.574: DEBUG/dalvikvm(119): GC freed 10191 objects / 487632 bytes in 4140ms
07-25 09:53:07.734: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:07.937: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:08.204: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:08.414: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:08.644: INFO/System.out(643): waiting for debugger to settle...
07-25 09:53:08.854: INFO/System.out(643): debugger has settled (1465)
07-25 09:53:09.053: ERROR/gralloc(52): [unregister] handle 0x1338a8 still locked (state=40000001)
07-25 09:53:09.473: DEBUG/dalvikvm(643): GC freed 650 objects / 52080 bytes in 159ms
07-25 09:53:09.993: INFO/ActivityManager(52): Displayed activity com.cryptooo.lol/.SimpleCryptoActivity: 4007 ms (total 4007 ms)
07-25 09:53:13.174: DEBUG/dalvikvm(643): GC freed 73 objects / 93640 bytes in 73ms
07-25 09:53:18.924: DEBUG/dalvikvm(264): GC freed 43 objects / 2024 bytes in 3859ms
07-25 09:53:21.714: DEBUG/dalvikvm(98): GC freed 2725 objects / 159280 bytes in 1649ms
07-25 09:53:22.123: DEBUG/dalvikvm(643): GC freed 126 objects / 900328 bytes in 69ms
07-25 09:53:22.154: INFO/dalvikvm-heap(643): Grow heap (frag case) to 12.648MB for 2092136-byte allocation
07-25 09:53:22.335: DEBUG/dalvikvm(643): GC freed 41 objects / 1592 bytes in 176ms
07-25 09:53:30.224: DEBUG/dalvikvm(643): GC freed 3 objects / 1042080 bytes in 70ms
07-25 09:53:30.294: INFO/dalvikvm-heap(643): Grow heap (frag case) to 15.651MB for 4192360-byte allocation
07-25 09:53:30.474: DEBUG/dalvikvm(643): GC freed 0 objects / 0 bytes in 172ms
07-25 09:53:36.184: DEBUG/dalvikvm(643): GC freed 4 objects / 2096320 bytes in 75ms
07-25 09:53:36.214: INFO/dalvikvm-heap(643): Grow heap (frag case) to 16.091MB for 2557851-byte allocation
07-25 09:53:36.413: DEBUG/dalvikvm(643): GC freed 0 objects / 0 bytes in 200ms
07-25 09:53:36.543: DEBUG/dalvikvm(643): GC freed 54 objects / 2936 bytes in 73ms
07-25 09:53:36.583: INFO/dalvikvm-heap(643): Grow heap (frag case) to 18.537MB for 2557856-byte allocation
07-25 09:53:36.766: DEBUG/dalvikvm(643): GC freed 0 objects / 0 bytes in 180ms

【问题讨论】:

您必须在崩溃日志中进行编辑。 他的意思是你修改你的问题以包括你的 logcat 输出的复制/粘贴。 我只是用 logcat 的输出更新问题 看起来日志没有显示崩溃。这张照片是你在坠机前拍的吗? 这里是 Logcat 的直接链接:i304.photobucket.com/albums/nn170/damcrew/Untitled-2.jpgi304.photobucket.com/albums/nn170/damcrew/Untitled-1-1.jpg 【参考方案1】:

关于加载加密图像: 您可以使用/assets 文件夹,它在您的工作区中与/res 处于同一级别。然后你把文件放在里面。假设它被称为“myfile.enc”。您应该使用AssetManager 来检索文件:

    AssetManager am = activity.getAssets();
    InputStream is = am.open("myfile.enc");

使用 InputStream,您可以将其写入ByteArrayOutputStream,然后获取字节,或者您可以将其传递给CipherInputstream,而不是调用Cipher.doFinal。如果你有一个相对较大的资源,这是要走的路。但是对于你的小测试,我认为字节版本是最简单的。

为了使 Bitmap 工作正常,我还将它放在 assets 文件夹下,然后使用相同的过程获取字节。 drawables 文件夹通常用于存放您将在 GUI 中使用的图像,因此您可以在 R.java 上使用它们的 ID。

【讨论】:

我无法理解活动的用途,因为它在这一行给了我一个错误:“活动无法解决”。是我的主要活动还是我需要添加的一些新变量。还有一个问题,如何在 ByteArrayOutputStream 中编写 Inputstream。在我的示例中是这样的吗: InputStream is=am.open("myfile.enc"); byte[] bytes = IOUtils.toByteArray(is);非常感谢耐心的朋友! 是的,活动是您的Activity 实例,如果您从活动中调用代码,请输入this。关于第二个问题,这是非常基本的,与这个线程无关,但关于名称,IOUtils.toByteArray 方法似乎正在做你想要的。 (那个类 IOUtils 不在 API 中,所以你应该比任何人都知道它是否有效)。 我可以使用 API 中的哪个类来代替 IOUtils,有什么想法吗? 天啊,如果它有效,那就使用它!我并不是说它的实现一定不好,因为我还没有看到代码。如果它不起作用,AFAIK 在 API 中没有将 InputStream 转储到 OutputStream 的类,但是在 while 循环中很容易做到(使用你最喜欢的互联网搜索引擎看看如何)。这种方法一旦完成,就会成为每个程序员的基本实用程序类的一部分。【参考方案2】:

两件事:

-您正在 Ui 线程(AKA 事件线程)上执行一项广泛的任务。这是一种非常糟糕的处理方式,因为您阻塞了 GUI,如果您在上面花费太多时间,操作系统将启动“应用程序无响应”错误。

-我认为您没有在 onCreate 中启动视图。

【讨论】:

你也在使用错误的语言命名资源 XD 这个其实不是我写的。我对Android中的加解密不是很熟悉。只是为了测试AES算法的速度,我想修改一个示例。 尝试在 onCreate 中启动一个实际的视图,即使你不需要它。此外,在启动视图后,在单独的线程上启动您的任务。这不是启动任务的最佳方式,但您的应用似乎仅用于测试,所以没关系。对于更严重的应用程序,您应该考虑使用 AsyncTask。 我解决了视图的问题,但不确定如何做另一部分。我在互联网上搜索了一个可以帮助我的例子,但我找不到一个好的它。 简单。将您的测试代码包装在一个方法中,然后执行new Thread()public void run()//Your code here.start();

以上是关于Android 加密/解密问题 (AES)的主要内容,如果未能解决你的问题,请参考以下文章

Android 加密/解密问题 (AES)

android Aes加密解密和Des加密解密

Android AES 加密解密

Android加密算法之AES加密和解密实现

Android AES加密解密工具类

为啥windows下aes解密android上的加密文件失败