Android中的加密/解密

时间:2019-02-07 08:12:27

标签: android encryption aes

我已经在Android中使用静态密码(即“加密”)进行了加密。加密工作正常并加密数据。但是,当我尝试解密加密的文本时,它不会显示。要解密的代码如下。

public String decrypt(String msg, String inputPassword) throws Exception{
    SecretKeySpec key= generateKey(inputPassword);
    Cipher c = Cipher.getInstance(AES);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decodedValue= Base64.decode(msg, Base64.DEFAULT);

    /*If this line is present the encrypted message is not seen*/
    byte[] decValue = c.doFinal(Base64.decode(decodedValue, 
Base64.DEFAULT));
    String decryptedValue = new String(decodedValue);
    String decryptedValue = new String(decValue, StandardCharsets.UTF_8);
    return decryptedValue;
}

启用代码(在注释下方)。该消息不显示。但是当一行被评论时。这显示在消息框中

After the code is commented.

这是加密和密钥生成方法。

public String encrypt(String message, String inputPassword) throws Exception{
    SecretKeySpec key = generateKey(inputPassword);
    Cipher c = Cipher.getInstance(AES);
    c.init(c.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(message.getBytes());
    String encryptedValue = Base64.encodeToString(encVal, Base64.DEFAULT);
    return encryptedValue;
}

//For generating key for encryption
public SecretKeySpec generateKey(String inputPassword) throws  Exception{
    final MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] bytes = inputPassword.getBytes("UTF-8");
    digest.update(bytes, 0, bytes.length);
    byte[] key = digest.digest();
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    return secretKeySpec;
}

日志如下 enter image description here

也不维护API级别...我也不知道在哪里设置。 enter image description here

1 个答案:

答案 0 :(得分:1)

您可以尝试更改吗

String decryptedValue = new String(decodedValue)

对此

String decryptedValue = new String(decodedValue, StandardCharsets.UTF_8)

对于您的错误,请尝试更改为此内容

c.doFinal(Base64.decode(decodedValue, Base64.DEFAULT))