Java AES 不解密阿拉伯语

Mon*_*ghi 3 java eclipse encryption aes

我正在 Eclipse 上加密和解密字符串。我正在使用以下功能:

private final static String ALGORITHM = "AES";


    public static String cipher(String secretKey, String data) throws Exception {



        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 128, 256);

        SecretKey tmp = factory.generateSecret(spec);

        SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);



        Cipher cipher = Cipher.getInstance(ALGORITHM);

        cipher.init(Cipher.ENCRYPT_MODE, key);



        return toHex(cipher.doFinal(data.getBytes()));

    }


    public static String decipher(String secretKey, String data) throws Exception {



        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 128, 256);

        SecretKey tmp = factory.generateSecret(spec);

        SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);



        Cipher cipher = Cipher.getInstance(ALGORITHM);



        cipher.init(Cipher.DECRYPT_MODE, key);



        return new String(cipher.doFinal(toByte(data)));

    }


    private static byte[] toByte(String hexString) {

        int len = hexString.length()/2;



        byte[] result = new byte[len];



        for (int i = 0; i < len; i++)

            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();

        return result;

    }


    public static String toHex(byte[] stringBytes) {

        StringBuffer result = new StringBuffer(2*stringBytes.length);



        for (int i = 0; i < stringBytes.length; i++) {

            result.append(HEX.charAt((stringBytes[i]>>4)&0x0f)).append(HEX.charAt(stringBytes[i]&0x0f));

        }



        return result.toString();

    }
    private final static String HEX = "0123456789ABCDEF";
Run Code Online (Sandbox Code Playgroud)

我正在处理的字符串包含英语和阿拉伯语字符。当我解密字符串时,阿拉伯字符被一个问号 ( ? ) 替换

我怎么解决这个问题 ?

Mar*_*eel 5

问题是你使用data.getBytes()(和secretKey.getBytes())。此方法使用操作系统上的默认编码。例如,在 Windows 上的西欧,此默认值Cp1252不包含阿拉伯语,因此将不受支持的字符转换为?.

data.getBytes("UTF-8)创建字符串时,您也需要使用和 。

底线:始终明确您的角色集!