我尝试使用AES算法解密String文本,但我发现了许多教程,但在尝试解密字符串时仍然遇到相同的错误。
这是我的班级:
EditText inputText, inputPass;
TextView out;
Button btnEnc, btnDec;
String outputString;
private static final String AES_MODE = "AES";
View.OnClickListener encryption= new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
outputString= encrypt(inputText.getText().toString(),inputPass.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
out.setText(outputString);
}
};
View.OnClickListener decryption= new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
outputString= decrypt(outputString,inputPass.getText().toString());
} catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}
out.setText(outputString);
}
};
private String encrypt(String data, String pass)throws Exception{
SecretKeySpec key= generateKey(pass);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.ENCRYPT_MODE,key);
byte[] encVal= c.doFinal(data.getBytes());
String encryptedValue= Base64.encodeToString(encVal,Base64.DEFAULT);
return encryptedValue;
}
private String decrypt(String cadena, String password)throws Exception{
SecretKeySpec keySpec= generateKey(password);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decValue= Base64.decode(cadena, Base64.DEFAULT);
String decryptedValue= new String((decValue));
return decryptedValue;
}
private SecretKeySpec generateKey(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest= MessageDigest.getInstance("SHA-256");
byte[] bytes= password.getBytes("UTF-8");
digest.update(bytes,0,bytes.length);
byte[] key= digest.digest();
SecretKeySpec secretKeySpec= new SecretKeySpec(key, "AES");
return secretKeySpec;
}
问题是当我尝试检索Decrypted字符串时,因为它返回了这个:
如您所见,输出文本包含Unicode字符,而不是我加密的文本。会出现什么问题?
答案 0 :(得分:1)
您忘记在解密方法中实际调用您的密码。
private String decrypt(String cadena, String password)throws Exception{
SecretKeySpec keySpec= generateKey(password);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decValue= c.doFinal(Base64.decode(cadena, Base64.DEFAULT));
// ^^^^^^^^^ add this
String decryptedValue= new String((decValue));
return decryptedValue;
}
此外,在从byte[]
转换为String
时,您应始终明确指定编码,反之亦然。