Как исправить длину ключа 256 бит в Android - PullRequest
1 голос
/ 02 августа 2020

В моем приложении я хочу загрузить зашифрованный файл с AES, CB C и расшифровать этот файл в свое приложение!
Я пишу ниже коды в своем приложении, но после того, как приложение покажет мне эту ошибку в logcat:

E/newDecryptLog: 0 : Key length not 128/192/256 bits.

Мой пароль: 7BOF%aZQMpfJ#2wUS*S6!@K+ZB$Sz+J0

Мои коды:

public class EncryptDecryptUtils {

    public static EncryptDecryptUtils instance = null;
    private static PrefUtils prefUtils;

    public static EncryptDecryptUtils getInstance(Context context) {

        if (null == instance)
            instance = new EncryptDecryptUtils();

        if (null == prefUtils)
            prefUtils = PrefUtils.getInstance(context);

        return instance;
    }

    public static byte[] encode(SecretKey yourKey, byte[] fileData)
            throws Exception {
        byte[] data = yourKey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, KEY_SPEC_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(fileData);
    }

    public static byte[] decode(SecretKey yourKey, byte[] fileData)
            throws Exception {
        byte[] decrypted;
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
        cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        decrypted = cipher.doFinal(fileData);
        return decrypted;
    }

    public void saveSecretKey(SecretKey secretKey) {
        String encodedKey = Base64.encodeToString(secretKey.getEncoded(), Base64.NO_WRAP);
        prefUtils.saveSecretKey(encodedKey);
    }

    public SecretKey getSecretKey() {
        String encodedKey = "7BOF%aZQMpfJ#2wUS*S6!@K+ZB$Sz+J0";
        if (null == encodedKey || encodedKey.isEmpty()) {
            SecureRandom secureRandom = new SecureRandom();
            KeyGenerator keyGenerator = null;
            try {
                keyGenerator = KeyGenerator.getInstance(KEY_SPEC_ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            keyGenerator.init(OUTPUT_KEY_LENGTH, secureRandom);
            SecretKey secretKey = keyGenerator.generateKey();
            saveSecretKey(secretKey);
            return secretKey;
        }

        byte[] decodedKey = Base64.decode(encodedKey, Base64.NO_WRAP);
        SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, KEY_SPEC_ALGORITHM);
        return originalKey;
    }
}

Я использовал эти коды для вышеуказанного класса:

@Nullable
public static byte[] decryptFile(Context context, String fileName) {
    try {
        byte[] fileData = FileUtils.readFile(FileUtils.getFilePath(context, fileName));
        byte[] decryptedBytes = EncryptDecryptUtils.decode(EncryptDecryptUtils.getInstance(context).getSecretKey(), fileData);
        return decryptedBytes;
    } catch (Exception e) {
        Log.e("newDecryptLog", "0 : " + e.getMessage());
    }
    return null;
}

Но когда я использую этот метод перехвата и покажите мне ошибку выше!

Как я могу это исправить?

1 Ответ

1 голос
/ 02 августа 2020

Вы можете уменьшить свой getSecretKey-метод, так как ваше предложение if никогда не будет иметь значение false. Ваш encodedKey НЕ является строкой Base64, но является прямым вводом и может использоваться в качестве ключа:

Поскольку я нахожусь на рабочем столе - Java Я не знаю, доступны ли StandardCharsets в Android.

public SecretKey getSecretKey() {
        String encodedKey = "7BOF%aZQMpfJ#2wUS*S6!@K+ZB$Sz+J0";
        return new SecretKeySpec(encodedKey.getBytes(StandardCharsets.UTF_8), KEY_SPEC_ALGORITHM);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...