Android SMS加密在解密时出现异常

Android SMS加密在解密时出现异常,android,sms,encryption,Android,Sms,Encryption,我正在开发一个android应用程序来处理短信。 我已经完成了这个应用程序,但还有最后一件事没有解决:加密 我如何计算出加密传入的短信 public class enc { private String iv = "fedcba9876543210"; private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher;

我正在开发一个android应用程序来处理短信。 我已经完成了这个应用程序,但还有最后一件事没有解决:加密

我如何计算出加密传入的短信

public class enc {

        private String iv = "fedcba9876543210";
        private IvParameterSpec ivspec;
        private SecretKeySpec keyspec;
        private Cipher cipher;

        private String SecretKey = "0123456789abcdef";

        public enc()
        {
            ivspec = new IvParameterSpec(iv.getBytes());

            keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

            try {
                cipher = Cipher.getInstance("AES/CBC/NoPadding");
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public String encrypt(String text) throws Exception
        {
            if(text == null || text.length() == 0)
                throw new Exception("Empty string");

            byte[] encrypted = null;

            try {
                cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

                encrypted = cipher.doFinal(padString(text).getBytes());
            } catch (Exception e)
            {           
                throw new Exception("[encrypt] " + e.getMessage());
            }
            String s = new String(encrypted);
            Log.v("TAG", s);


            return s;
        }

        public String decrypt(String code) throws Exception
        {
            if(code == null || code.length() == 0)
                throw new Exception("Empty string");

            byte[] decrypted = null;

            try {
                cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

                decrypted = cipher.doFinal(hexToBytes(code));
            } catch (Exception e)
            {
                throw new Exception("[decrypt] " + e.getMessage());
            }
            Log.v("TAG", decrypted.toString());
            String s = new String(decrypted);
            Log.v("TAG", s);
            return s;
        }



        public static String bytesToHex(byte[] data)
        {
            if (data==null)
            {
                return null;
            }

            int len = data.length;
            String str = "";
            for (int i=0; i<len; i++) {
                if ((data[i]&0xFF)<16)
                    str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
                else
                    str = str + java.lang.Integer.toHexString(data[i]&0xFF);
            }
            return str;
        }


        public static byte[] hexToBytes(String str) {
            if (str==null) {
                return null;
            } else if (str.length() < 2) {
                return null;
            } else {
                int len = str.length() / 2;
                byte[] buffer = new byte[len];
                for (int i=0; i<len; i++) {
                    buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                }
                return buffer;
            }
        }



        private static String padString(String source)
        {
          char paddingChar = ' ';
          int size = 16;
          int x = source.length() % size;
          int padLength = size - x;

          for (int i = 0; i < padLength; i++)
          {
              source += paddingChar;
          }

          return source;
        }
    }

您可能希望发布完整的堆栈跟踪。目前,您的代码存在三个问题:

您的密钥很弱:您应该只使用一些ASCII字符构造一个密钥。这严重限制了密钥空间,并使暴力破解密钥变得容易 不要使用非标准填充。使用Cipher.getInstanceAES/CBC/PKCS5Padding获得适当的填充 不要使用固定IV,为每个加密操作生成一个随机IV
此外,使用getBytes可能会产生奇怪的结果,因为编码是未定义的,使用平台默认值。它在Android上可能是一致的,但是使用getBytesUTF-8来确保从相同的字符串中获得相同的字节

升级了logcat,请检查它,并检查您的输入和输出。您的加密代码似乎试图将加密的~random字节转换为字符串,而解密代码似乎希望使用十六进制编码的字符串。正如@GregS所说的,您需要更好地理解Java字符和字节之间的区别,因为您的代码揭示了根本的误解。从加密的输出构造一个字符串是没有意义的,可能也行不通的。此外,您使用toString对于byte[]数组没有意义。@GregS如果我甚至不使用toString方法并使用byte数组,itt仍然会给出相同的例外情况。我很欣赏这一点,但我的观点是,您需要更熟悉字符和字节之间的差异。
04-24 13:56:17.191: V/(2031): Message Recieved
04-24 13:56:22.811: V/TAG(2031): [B@44ebb318
04-24 13:56:22.811: V/Encrypted(2031): [B@44ebb318
04-24 13:56:22.931: W/System.err(2031): java.lang.Exception: [decrypt] unable to parse '[B' as integer
04-24 13:56:22.941: W/System.err(2031):     at sms.app.enc.decrypt(enc.java:86)
04-24 13:56:22.951: W/System.err(2031):     at sms.app.SMSReceiver.onReceive(SMSReceiver.java:86)
04-24 13:56:22.961: W/System.err(2031):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810)
04-24 13:56:22.961: W/System.err(2031):     at android.app.ActivityThread.access$3200(ActivityThread.java:125)
04-24 13:56:22.970: W/System.err(2031):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
04-24 13:56:22.981: W/System.err(2031):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 13:56:22.981: W/System.err(2031):     at android.os.Looper.loop(Looper.java:123)
04-24 13:56:22.991: W/System.err(2031):     at android.app.ActivityThread.main(ActivityThread.java:4627)
04-24 13:56:23.001: W/System.err(2031):     at java.lang.reflect.Method.invokeNative(Native Method)
04-24 13:56:23.001: W/System.err(2031):     at java.lang.reflect.Method.invoke(Method.java:521)
04-24 13:56:23.011: W/System.err(2031):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-24 13:56:23.021: W/System.err(2031):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-24 13:56:23.021: W/System.err(2031):     at dalvik.system.NativeStart.main(Native Method)