在Android上的加密/解密

问题描述 投票:0回答:1

我已经做了加密的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

android encryption aes
1个回答
1
投票

你可以尝试改变这种

String decryptedValue = new String(decodedValue)

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

而对于你的错误,请尝试更改为此

c.doFinal(Base64.decode(decodedValue, Base64.DEFAULT))
© www.soinside.com 2019 - 2024. All rights reserved.