Android AES解密返回稀有字符V2.0

时间:2018-03-18 10:53:13

标签: java android encryption aes

最近我发布了一个关于这个主题的问题,但当我试图解密在UTF8上编码的AES字符串时,事情变得有点奇怪

在以下几行中,我读取了字符串AES加密,并返回以下字符串:RnLObq9hdUDGp9S2pxC1qjQXekuf9g6i / 5bQfKilYn4 =

public static final String AesKey256 ="ZzRtNDNuY3J5cHRrM3kuLi4=";
//This reads the String and stores on res.getContents()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult res= IntentIntegrator.parseActivityResult(requestCode, resultCode,data);
    if(res!=null){
        if (res.getContents() == null) {
            Toast.makeText(this,"Captura cancelada",Toast.LENGTH_SHORT).show();
        }else{
            try {
                String cadena= decrypt(res.getContents());
                out.setText(cadena);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
//provide the res.getContents() to decrypt method, wich its the String i've recently read
 private String decrypt(String cadena)throws Exception{
    SecretKeySpec keySpec= generateKey(AesKey256); //HERE
    Cipher c= Cipher.getInstance(AES_MODE);
    c.init(Cipher.DECRYPT_MODE,keySpec);
    byte[] decodedValue= Base64.decode(cadena, Base64.DEFAULT);
    byte[] decValue= c.doFinal(decodedValue);/* c.doFinal(decodedValue);*/
    String decryptedValue= new String((decValue), "UTF-8");
    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;
}

我只使用解密方法,但它仍然返回此字符: this shows after read the string

我花了好几个小时寻找解决方案,但现在没有任何作用......希望有人能帮我一把!

最诚挚的问候!

EDIT 这是如何在C#中加密的

private const string AesIV256 = "IVFBWjJXU1gjRURDNFJGVg==";
        private const string AesKey256 = "ZzRtNDNuY3J5cHRrM3kuLi4=";

        public static string Encrypt(string text)
        {
            var sToEncrypt = text;
            var rj = new RijndaelManaged()
            {
                Padding = PaddingMode.Zeros,
                Mode = CipherMode.ECB,
                KeySize = 256,
                BlockSize = 256,
            };

            var key = Convert.FromBase64String(AesKey256);
            var IV = Convert.FromBase64String(AesIV256);

            var encryptor = rj.CreateEncryptor(key, IV);

            var msEncrypt = new MemoryStream();
            var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            var toEncrypt = Encoding.UTF8.GetBytes(sToEncrypt);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            var encrypted = msEncrypt.ToArray();

            return (Convert.ToBase64String(encrypted));
        }

1 个答案:

答案 0 :(得分:0)

做到了!

经过长时间的搜索,感谢所有回答这篇文章的人,我使用了充气城堡图书馆,我通过以下方式解密了所需的字符串:

public static String decrypt(String valueToDecrypt) throws Exception {
    AESCrypt enc = new AESCrypt();
    return new String(enc.decryptInternal(valueToDecrypt)).trim();
}

private byte[] decryptInternal(String code) throws Exception {
    if (code == null || code.length() == 0) {
        throw new Exception("Empty string");
    }

    byte[] decrypted = null;
    try {


        byte[] key= SecretKey.getBytes("UTF-8");
        PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new RijndaelEngine(256), new ZeroBytePadding());
        CipherParameters params= new KeyParameter(key);`
        // false because its going to decrypt
        c.init(false,params);
        decrypted= GetData(c,(Base64.decode(code,Base64.DEFAULT));

    } catch (Exception e) {
        throw new Exception("[decrypt] " + e.getMessage());
    }
    return decrypted;
}


private static byte[] GetData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException
{
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    byte[] cipherArray = new byte[actualLength];
    for (int x = 0; x < actualLength; x++) {
        cipherArray[x] = outBuf[x];
    }
    return cipherArray;
}