Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android加密在发布应用程序时失败,但在调试时失败_Java_Android_Encryption - Fatal编程技术网

Java Android加密在发布应用程序时失败,但在调试时失败

Java Android加密在发布应用程序时失败,但在调试时失败,java,android,encryption,Java,Android,Encryption,我正在使用下面的实用程序类加密Android上的敏感数据。我使用下面的方法是因为我希望它能在运行AndroidL或更早版本的设备上工作 import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.security.KeyPairGeneratorSpec; import android.util.Base64; import j

我正在使用下面的实用程序类加密Android上的敏感数据。我使用下面的方法是因为我希望它能在运行AndroidL或更早版本的设备上工作

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.util.Base64;

import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;
import java.util.Calendar;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.security.auth.x500.X500Principal;

public class Encryptor
{
    private static final String KEY_ALIAS = "xxxxxx";
    private static final String SECRET_PREF_NAME = "xxxxx";
    private static final String SECRET_KEY_NAME = "xxxxx";
    private static final String RSA_MODE = "RSA/ECB/PKCS1Padding";
    private static final String AES_MODE = "AES/ECB/PKCS7Padding";

    private static  KeyStore.PrivateKeyEntry getKeyPairEntry(Context ctx)
        throws
            IOException,
            KeyStoreException,
            NoSuchAlgorithmException,
            NoSuchProviderException,
            InvalidAlgorithmParameterException,
            UnrecoverableEntryException,
            CertificateException
    {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        if (!keyStore.containsAlias(KEY_ALIAS))
        {
            // Generate a key pair for encryption
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 10);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx)
                .setAlias(KEY_ALIAS)
                .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            kpg.initialize(spec);
            kpg.generateKeyPair();
        }

        return (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null);
    }

    private static  byte[] encryptSecret(Context ctx, byte[] secret)
            throws
            IOException,
            KeyStoreException,
            NoSuchAlgorithmException,
            NoSuchProviderException,
            InvalidAlgorithmParameterException,
            UnrecoverableEntryException,
            CertificateException,
            NoSuchPaddingException,
            InvalidKeyException,
            BadPaddingException,
            IllegalBlockSizeException
    {
        KeyStore.PrivateKeyEntry privateKeyEntry = getKeyPairEntry(ctx);

        Cipher cipher;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        {
            cipher = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL"); // error in android 6: InvalidKeyException: Need RSA private or public key
        }
        else
        {
            cipher = Cipher.getInstance(RSA_MODE, "AndroidKeyStoreBCWorkaround"); // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
        }

        cipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());
        return cipher.doFinal(secret);
    }

    private static  byte[] decryptSecret(Context ctx, byte[] encrypted)
            throws
            UnrecoverableEntryException,
            NoSuchAlgorithmException,
            IOException,
            KeyStoreException,
            CertificateException,
            NoSuchProviderException,
            InvalidAlgorithmParameterException,
            NoSuchPaddingException,
            InvalidKeyException,
            BadPaddingException,
            IllegalBlockSizeException
    {
        KeyStore.PrivateKeyEntry privateKeyEntry = getKeyPairEntry(ctx);

        Cipher cipher;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        {
            cipher = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL"); // error in android 6: InvalidKeyException: Need RSA private or public key
        }
        else
        {
            cipher = Cipher.getInstance(RSA_MODE, "AndroidKeyStoreBCWorkaround"); // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
        }

        cipher.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
        return cipher.doFinal(encrypted);
    }

    private static  void generateSecretIfNecessary(Context ctx)
            throws
            IOException,
            CertificateException,
            NoSuchAlgorithmException,
            InvalidKeyException,
            UnrecoverableEntryException,
            InvalidAlgorithmParameterException,
            NoSuchPaddingException,
            NoSuchProviderException,
            KeyStoreException,
            BadPaddingException,
            IllegalBlockSizeException
    {
        SharedPreferences pref = ctx.getSharedPreferences(SECRET_PREF_NAME, Context.MODE_PRIVATE);
        String encryptedKeyB64 = pref.getString(SECRET_KEY_NAME, null);
        if (encryptedKeyB64 == null)
        {
            KeyGenerator gen = KeyGenerator.getInstance("AES");
            gen.init(256); /* 256-bit AES */
            SecretKey secret = gen.generateKey();
            byte[] encryptedKey = encryptSecret(ctx, secret.getEncoded());
            encryptedKeyB64 = Base64.encodeToString(encryptedKey, Base64.DEFAULT);
            SharedPreferences.Editor edit = pref.edit();
            edit.putString(SECRET_KEY_NAME, encryptedKeyB64);
            edit.commit();
        }
    }

    private static Key getSecret(Context ctx)
            throws
            IOException,
            CertificateException,
            NoSuchAlgorithmException,
            InvalidKeyException,
            UnrecoverableEntryException,
            InvalidAlgorithmParameterException,
            NoSuchPaddingException,
            KeyStoreException,
            NoSuchProviderException,
            BadPaddingException,
            IllegalBlockSizeException
    {
        generateSecretIfNecessary(ctx);

        SharedPreferences pref = ctx.getSharedPreferences(SECRET_PREF_NAME, Context.MODE_PRIVATE);
        String encryptedSecretB64 = pref.getString(SECRET_KEY_NAME, null);
        byte[] encryptedSecret = Base64.decode(encryptedSecretB64, Base64.DEFAULT);
        byte[] key = decryptSecret(ctx, encryptedSecret);
        return new SecretKeySpec(key, "AES");
    }

    public static String encryptData(Context ctx, byte[] input) throws EncryptorException
    {
        try
        {
            Cipher c = Cipher.getInstance(AES_MODE, "BC");
            c.init(Cipher.ENCRYPT_MODE, getSecret(ctx));
            byte[] encryptedBytes = c.doFinal(input);
            return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
        }
        catch (InvalidKeyException | BadPaddingException | IOException | NoSuchPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | CertificateException | NoSuchProviderException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException e)
        {
            throw new EncryptorException("Failed to encrypt data", e);
        }
    }

    public static  byte[] decryptData(Context ctx, String encryptedBase64Encoded) throws EncryptorException
    {
        try
        {
            Cipher c = Cipher.getInstance(AES_MODE, "BC");
            c.init(Cipher.DECRYPT_MODE, getSecret(ctx));
            byte[] encrypted = Base64.decode(encryptedBase64Encoded, Base64.DEFAULT);
            byte[] decodedBytes = c.doFinal(encrypted);
            return decodedBytes;
        }
        catch (InvalidKeyException | BadPaddingException | IOException | NoSuchPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | CertificateException | NoSuchProviderException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException e)
        {
            throw new EncryptorException("Failed to decrypt data", e);
        }
    }
}
我无法进行很多调试,因为错误并没有真正指向任何地方。如果有人能帮忙,我会非常感激。在尝试加密/解密时,我可能也做了错误的事情。我也不确定我是否完全知道我在上面做什么。任何指点都将不胜感激

以下是我的清单权限的外观:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="xxxxxxxxxxxxxxx">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

</manifest>
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'

    defaultConfig {
        applicationId "com.bantuapp.bantu"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 44
        versionName "1.0"
        multiDexEnabled true
        vectorDrawables {
            useSupportLibrary true
        }
    }
}

加密负载上似乎缺少填充,请确保设置了填充,例如:
AES/CBC/PKCS7Padding


指示要解密的数据与密码的块大小不匹配。

如果加密的有效负载上缺少填充,请确保设置了填充,例如:
AES/CBC/PKCS7Padding


指示要解密的数据与密码的块大小不匹配。

是否已解决此问题?是否已解决此问题?
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'

    defaultConfig {
        applicationId "com.bantuapp.bantu"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 44
        versionName "1.0"
        multiDexEnabled true
        vectorDrawables {
            useSupportLibrary true
        }
    }
}