Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

android encryption

I want to encrypt/decrypt some passwords in the SQLite database of my application. To do that I have searched on the internet and I have found the AES algorithm. I have this code:

public String encript(String dataToEncrypt)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    // I'm using AES encription

    if(!dataToEncrypt.equals("")){
        String key = "FMVWf8d_sm#fz";

        Cipher c = Cipher.getInstance("AES");
        SecretKeySpec k;
        try {
            k = new SecretKeySpec(key.getBytes(), "AES");
            c.init(Cipher.ENCRYPT_MODE, k);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        return new String(c.doFinal(Base64.decode(dataToEncrypt)));
    }
    return "";
}

public String decript(String encryptedData)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    if(!encryptedData.equals("")){
        String key = "FMVWf8d_sm#fz";

        Cipher c = Cipher.getInstance("AES");
        SecretKeySpec k = new SecretKeySpec(Base64.decode(key), "AES");
        c.init(Cipher.DECRYPT_MODE, k);
        return new String(c.doFinal(Base64.decode(encryptedData)));
    }
    return "";
}

After running this I get this error on encrypt method:

01-27 14:50:51.698: ERROR/ACTIVITY(782): java.security.InvalidKeyException: Key length not 128/192/256 bits.

I have seen some other cases here on stackoverflow but I want to give the key to the AES not to generate it...

Can somebody help me with this? If there is other encryption method to use but without using another jars or external classes and to let me give the key.

Thank you very much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error message makes it perfectly clear: your encryption key must be of certain size: 128, 192 or 256 bits. And your key is 104 bits. Note, that as you want to use only printable characters in your key, the length of the key should be 192 or longer bits, cause your alphabet (set of characters that you use) makes encryption weaker.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...