javax.crypto中不同的工作在不同版本的Andr​​oid操作系统? [英] javax.crypto working differently in different versions of Android OS?

查看:149
本文介绍了javax.crypto中不同的工作在不同版本的Andr​​oid操作系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code段加密/解密在我的应用程序的数据库中的数据:

I'm using this code snippet to encrypt/decrypt data in my app's database:

http://www.androidsnippets.com/encryptdecrypt-strings

看来,javax.crypto.KeyGenerator.generateKey()操作的工作方式不同的安卓2.3.3操作系统比其他(previous?)版本。当然,这presents为我的用户,当他们从2.2升级他们的设备到2.3.3的一个主要问题和应用程序开始引发错误解密数据库。

It appears that the javax.crypto.KeyGenerator.generateKey() operation works differently in Android 2.3.3 OS than in other (previous?) versions. Naturally, this presents a major problem for my users when they upgrade their device from 2.2 to 2.3.3 and the app starts throwing errors decrypting the database.

这是一个已知的问题?我使用的密码库不正确?任何人对如何解决这个问题的任何建议,使加密2.2数据能够在2.3.3要解密?

Is this a known issue? Am I using the crypto library incorrectly? Anyone have any suggestions on how to address this so that data encrypted in 2.2 is able to be decrypted in 2.3.3?

我建立了一个测试程序,通过加密函数提要值。当我在2.2 AVD运行它,我得到一个结果。当我在2.3.3 AVD运行它,我得到一个不同的结果。

I built a test app that feeds values through the encrypt function. When I run it on a 2.2 AVD, I get one result. When I run it on a 2.3.3 AVD, I get a different result.

    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.os.Bundle;
    import android.widget.TextView;

    public class main extends Activity {
        TextView tvOutput;
        static String out;
        String TEST_STRING = "abcdefghijklmnopqrstuvwxyz";
        String PASSKEY = "ThePasswordIsPassord";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            tvOutput = (TextView) findViewById(R.id.tvOutput);
        }

        @Override
        public void onResume() {
            super.onResume();
            out = "";
            runTest();
            tvOutput.setText(out);
        }

        private void runTest() {
            out = "Test string: " + TEST_STRING + "\n";
            out += "Passkey: " + PASSKEY + "\n";
            try {
                out += "Encrypted: " + encrypt(PASSKEY, TEST_STRING) + "\n";
            } catch (Exception e) {
                out += "Error: " + e.getMessage() + "\n";
                e.printStackTrace();
            }

        }

        public static String encrypt(String seed, String cleartext)
        throws Exception {
            byte[] rawKey = getRawKey(seed.getBytes());
            byte[] result = encrypt(rawKey, cleartext.getBytes());
            return toHex(result) + "\n" + "Raw Key: " + String.valueOf(rawKey)
                    + "\n";
        }

        private static byte[] getRawKey(byte[] seed) throws Exception {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(seed);
            kgen.init(128, sr); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey();
            byte[] raw = skey.getEncoded();
            return raw;
        }

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

        public static String toHex(String txt) {
            return toHex(txt.getBytes());
        }

        public static String fromHex(String hex) {
            return new String(toByte(hex));
        }

        public static byte[] toByte(String hexString) {
            int len = hexString.length() / 2;
            byte[] result = new byte[len];
            for (int i = 0; i < len; i++)
                result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                        16).byteValue();
            return result;
        }

        public static String toHex(byte[] buf) {
            if (buf == null)
                return "";
            StringBuffer result = new StringBuffer(2 * buf.length);
            for (int i = 0; i < buf.length; i++) {
                appendHex(result, buf[i]);
            }
            return result.toString();
        }

         private final static String HEX = "0123456789ABCDEF";

        private static void appendHex(StringBuffer sb, byte b) {
            sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
        }
    }

我的main.xml中的布局是这样的:

My main.xml layout looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/tvOutput" />
    </LinearLayout>

我不能发布链接或图像,因为我是一个新用户,但是你可以破译的URL为以下两个图像,如果你想看到的结果:

I can't post links or images since I'm a new users, but you can decipher the URLs for the following two images if you want to see the results:

我从2.2得到:

..和2.3.3:

推荐答案

您在不当使用伪随机数生成器,它的种子作为密钥导出函数 - 这实在是非常糟糕的风格。伪随机数生成器SHA1PRNG是不是如AES标准 - 所以你永远不知道什么样的实现你得到的。 另请参见是否有SHA1PRNG标准

You are misusing a pseudo random number generator and it's seed as a key derivation function - this is really really bad style. The pseudo random number generator "SHA1PRNG" is not a standard like AES - therefore you never know what implementation you get. See also Is there a SHA1PRNG standard?

这让我毫无疑问,你会得到不同的结果。获得基于给定的种子确定性结果不是你可以从一个伪随机数函数需要的属性。

It makes me no wonder that you get different results. Getting a deterministic result based on a given seed is not a property you can expect from a pseudo random number functions.

如果你想来源于密码的加密密钥,请使用密钥导出函数像PKCS#5 / PBKDF2 。 PBKDF2的实现包含在充气城堡AFAIR。

If you want to derive a cryptographic key from a password please use a Key Derivation Function like PKCS #5 / PBKDF2. An implementation of PBKDF2 is AFAIR included in Bouncy Castle.

这篇关于javax.crypto中不同的工作在不同版本的Andr​​oid操作系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆