2 回答
TA貢獻1829條經驗 獲得超6個贊
這一行是錯誤的:
plainText.setText(new String(cipher.doFinal(plainText.getText().toString().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
如果我們把它分開,我們有類似的東西
byte [] cipherBytes = cipher.doFinal(plainText.getText().toString().getBytes(StandardCharsets.UTF_8)); plainText.setText(new String(cipherBytes, StandardCharsets.UTF_8);
問題是這cipherBytes是一個任意字節序列而不是字符串的字符。String 構造函數會悄悄地用其他東西替換無效字符,這是一個破壞數據的過程。
如果要顯示密碼字節或以其他方式將其發送到面向字符的通道,則必須對其進行編碼。通常編碼是 base64 或十六進制。要解密字符串,您必須先將其解碼為字節,然后再解密。
例子:
byte [] cipherBytes = cipher.doFinal(plainText.getText().toString().getBytes(StandardCharsets.UTF_8)); plainText.setText(Base64.encodeToString(cipherBytes, Base64.DEFAULT));
并解密:
byte[] cipherBytes = Base64.decode(plainText.getText().toString(), Base64.DEFAULT); byte[] decrypted = cipher.doFinal(cipherBytes);
TA貢獻1862條經驗 獲得超7個贊
byte[] decrypted = cipher.doFinal(plainText.getText().toString().getBytes(StandardCharsets.UTF_8));
由于 的調用,此行可能無法正常工作getBytes(StandardCharsets.UTF_8)。如果您EditText是十六進制表示,請嘗試將其轉換為字符串,然后調用getBytes(). 例如
public static byte[] convertHexStringToByteArray(String hexString) {
int l = hexString.length();
byte[] data = new byte[l/2];
for (int i = 0; i < l; i += 2) {
data[i/2] = (byte)((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16));
}
return data;
}
添加回答
舉報
