BadPaddingException in Android encrypt

前端 未结 4 1105
小鲜肉
小鲜肉 2021-02-10 10:37

I am making an Android application and I want to encrypt a String before sending it to a DataBase, and encrytpion is correct. The problem happens when decrypting the String beca

4条回答
  •  温柔的废话
    2021-02-10 11:30

    For those who wish to use String and Base64-encoding for usage with a database you can use these (slightly rewritten) functions from Mike Keskinov (and xalien on Anddev.org).

    public String encrypt(String str) 
    {
        try {
    
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");
    
            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);
    
            // Encode bytes to base64 to get a string 
            return new String(Base64.encode(enc,0));
    
        } catch (BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {       
        }
        return null;
    }
    
    public String decrypt(String str) 
    {
        try {
    
            // Decode base64 to get bytes           
            byte[] dec = Base64.decode(str, 0);
    
            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);
    
            // Decode using utf-8
            return new String(utf8, "UTF8");
    
        } catch (BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {       
        }
        return null;
    }
    

    This code also uses the built-in Android Base64 libraries, so no need for importing any additional external libraries.

    Something I didn't realise at first was how to actually use this class from another class (my ignorance). Here's a simple example:

    StringEncrypter se = new StringEncrypter("mypass");
    String decryptedString = se.decrypt(encryptedString);
    

    One more thing on Base64. I found out the hard way that Base64 encoding adds a '/n' linefeed character (0x0a) whenever the string gets longer than 76 characters. This severely messes up the decrypt results. To strip out these newline characters you can add something like:

    b64_enc_str = se.encrypt(plaintext_str);
    str = b64_enc_str.replace("/n","");
    

    Hopefully it helps someone.

提交回复
热议问题