4

SharedPreferencesに保存するためにAndroidデータの暗号化を行っています。GCMParameterSpec は、私がAES/GCM/NoPadding暗号化に使用している API 19 で Android に導入されました。これは私がそれを実装している方法です:

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, getSecretKey(context),new GCMParameterSpec(128,Base64.decode(myGeneratedIV, Base64.DEFAULT)));

私の問題は、Android 4.4.2 (API 19) で上記のエラーがスローされることですが、API 21 からは機能します。

例外について、Android ドキュメントから:

指定されたアルゴリズム パラメータがこの暗号に不適切である場合、またはこの暗号がアルゴリズム パラメータを必要とし、params が null である場合、または指定されたアルゴリズム パラメータが法的な制限を超える暗号強度を暗示している場合 (構成された管轄ポリシー ファイルから決定)。

私の質問は次のとおりです。この動作には特定の理由がありますか? initCipherのメソッドがパラメーターを識別しないのはなぜですか?

特定の IV を指定せずに暗号化を試みました。

c.init(Cipher.ENCRYPT_MODE, getSecretKey(context));

そして、同じ方法で復号化しようとすると:

c.init(Cipher.DECRYPT_MODE, getSecretKey(context));

GCMParameterSpec復号化には a が必要であるという同じ例外 (InvalidAlgorithmParameterException) をスローします。

GCMParameterSpec復号化のみを指定しようとしましたが、不明なパラメーターの型の例外が発生します。

どんな助けでも大歓迎です

4

3 に答える 3

-3

このコードを試してください...

    private static final String Key = "0123456789abcdef";

public static SecretKey generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    return new SecretKeySpec(Key.getBytes("UTF-8"), "AES");
}

public static byte[] encryptMsg(String message, SecretKey secret)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

    Cipher cipher;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    return cipher.doFinal(message.getBytes("UTF-8"));
}

public static String decryptMsg(byte[] cipherText, SecretKey secret)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {

    Cipher cipher;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret);
    return new String(cipher.doFinal(cipherText), "UTF-8");
}
于 2017-03-21T13:57:20.980 に答える