在设备上找不到 decodeHex 方法,但在模拟器上工作

decodeHex method not found on Device, but working on Emulator

我正在做RSA加密的项目,需要用到Apache commons-codec的方法,即:

这两种方法在 Android 模拟器上工作正常,但它会 return 在设备

上出现 NoSuchMethodError
public String RSADecrypt(final String message) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey());
            byte[] decryptedBytes = cipher.doFinal(Hex.decodeHex(message));
            return new String(decryptedBytes);
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (DecoderException e) {
            e.printStackTrace();
        }
        return "";
    }
java.lang.NoSuchMethodError: No static method decodeHex(Ljava/lang/String;)[B in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.boot.jar)

一些 Android 版本包含旧版本的 Apache commons-codec 库 (1.3),其中 decodeHex(String) 方法尚不存在。请尝试调用 decodeHex(char[])。 IE。像这样修改您的代码:

byte[] decryptedBytes = cipher.doFinal(Hex.decodeHex(message.toCharArray()));

这应该适用于 commons-codec v1.3。