我正在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";
我正在处理的字符串包含英语和阿拉伯字符。当我解密字符串时,阿拉伯字符被问号(?)代替。
我怎么解决这个问题 ?
问题是您使用data.getBytes()
(和secretKey.getBytes()
)。此方法使用操作系统上的默认编码。例如,在Windows上的西欧,此默认值Cp1252
不包含阿拉伯语,因此将不支持的字符转换为?
。
data.getBytes("UTF-8)
创建String时,还需要使用和。
底线:始终明确显示您的字符集!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句