我正在開發一個跨平臺的加密系統。其中一個要求是在應用程序代碼中輕鬆加密和解密字符串。編碼和解碼UTF-8字節數組和字符串
加密類完美地工作,但我在Java端的字符串編碼遇到麻煩。
目前,我有以下的靜態方法:解密時
public static String encrypt(String key, String data)
{
byte[] decoded_key;
byte[] decoded_data;
try
{
decoded_key = key.getBytes("UTF-8");
decoded_data = data.getBytes("UTF-8");
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
if(decoded_key.length != 16)
throw new IllegalArgumentException("Key length must be of 16 bytes. Given is " + decoded_key.length + ".");
try
{
return(IOUtils.toString(encrypt(decoded_key, decoded_data), "UTF-8"));
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
}
public static String decrypt(String key, String data)
{
byte[] decoded_key;
byte[] decoded_data;
try
{
decoded_key = key.getBytes("UTF-8");
decoded_data = data.getBytes("UTF-8");
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
if(decoded_key.length != 16)
throw new IllegalArgumentException("Key length must be of 16 bytes. Given is " + decoded_key.length + ".");
try
{
return(IOUtils.toString(decrypt(decoded_key, decoded_data), "UTF-8"));
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
}
我的單元測試失敗。我跑了一個測試,我比較了編碼的UTF-8數據的一個字節數組encoded_data
與IOUtils.toString(
encoded_data , "UTF-8").getBytes("UTF-8")
,由於某些原因,他們竟然是完全不同的數組。難怪我的解密算法失敗了。
從java字符串轉換爲UTF-8字節數組並返回到java字符串的正確過程是什麼?
爲什麼你首先將字符串表示爲「鍵」?據推測他們是任意字節?您可能首先將它們轉換爲字符串,從而破壞了您的密鑰。 – jtahlborn
業務需求。我的加密類使用字節。 – elite5472
你錯過了我的觀點。你怎麼把鑰匙保持爲字符串而不破壞它們? – jtahlborn