简体   繁体   中英

Android encryption/decryption issue (AES)

I need a little help here.So basically I have to make a test of AES encryption/decryption of an image in Android.I'm new in android programming and that's why a friend of mine give me an example of how to do it, but the problem is that when I run the sample it crashes after like 20-30 seconds and I'm not really sure what's happening.So can anyone please look at the code and tell me where is the problem.The sample code needs to do this : Encrypt and Decrypt the same image and show me a log with info, how long it takes to encrypt and decrypt the image.Thanks anyway!

Code :

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

}

and here is the 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

About loading the encrypted image: You can use the /assets folder, is in your workspace at the same level than /res . Then you place the file inside. Let's say it is called "myfile.enc". You should use the AssetManager to retrieve the file:

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

With the InputStream, you can write it to a ByteArrayOutputStream and then get the bytes, or you could pass it to a CipherInputstream instead of calling Cipher.doFinal . This is the way to go if you have a relatively large resource. But for your little test, I think the byte version is the easiest.

To get the Bitmap thing working, I would also put it under assets folder and then get the bytes with the same procedure. The drawables folder is generally for images you are going to use in the GUI, so you can use their ID's on R.java.

Two things:

-You are performing an extensive task on the Ui Thread (AKA event thread). This is very bad way of doing things, because you are blocking the GUI, and if you spend too much time on it, the OS will launch the "Application not responding" error.

-I think you are not launching a View in the onCreate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM