首页 > 解决方案 > 反对在 Android 上直接使用 javax.crypto

问题描述

我阅读了有关使用 Android 类在 Android 上进行加密的信息,例如:https ://android-developers.googleblog.com/2020/02/data-encryption-on-android-with-jetpack.html 。

但是 AndroidX Security 和其他类似的类android.security只能KeyGenParameterSpec在 API 23 及更高版本上使用。

所以我想知道是否有人反对javax.crypto直接在 Android 上使用类,例如在这里完成:https ://mkyong.com/java/java-aes-encryption-and-decryption/

public class EncryptorAesGcmPasswordFile {

    private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
    private static final int TAG_LENGTH_BIT = 128; // must be one of {128, 120, 112, 104, 96}
    private static final int IV_LENGTH_BYTE = 12;
    private static final int SALT_LENGTH_BYTE = 16;

    private static final Charset UTF_8 = Charset.forName("UTF-8");

    public static byte[] encrypt(byte[] pText, String password) throws Exception {

        byte[] salt = CryptoUtils.getRandomNonce(SALT_LENGTH_BYTE);

        byte[] iv = CryptoUtils.getRandomNonce(IV_LENGTH_BYTE);

        SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);

        Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);

        cipher.init(Cipher.ENCRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));

        byte[] cipherText = cipher.doFinal(pText);

        byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length)
                .put(iv)
                .put(salt)
                .put(cipherText)
                .array();

        return cipherTextWithIvSalt;

    }

    // ...
}

在 Android 上使用纯 javax.crypto 代码是否存在任何安全或其他问题?

标签: androidencryption

解决方案


推荐阅读