Mathi Vanan
Mathi Vanan

Reputation: 101

DES Encryption in Android

If I try encrypting "123456" with the key qwertykey I get UVEXg9fgBxo= as response with the online tool https://www.tools4noobs.com/online_tools/encrypt/.

But if I use android code I am getting 2XQNkfXlN6E= as encrypted value.

Can anyone explain to me how this can be achieved?

My code is:

public String encrypt(String plainTextPassword){
    String encrypted = "";
    try{
        DESKeySpec keySpec = new DESKeySpec("qwertykey".getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);
        byte[] cleartext = plainTextPassword.getBytes();

        Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
        cipher.init(Cipher.ENCRYPT_MODE, key);
        encrypted = Base64.encodeToString(cipher.doFinal(cleartext),Base64.DEFAULT);

    }catch (Exception e){

    }
    return encrypted;
}

Upvotes: 0

Views: 2985

Answers (1)

Rahim Khalid
Rahim Khalid

Reputation: 469

DES supports only a key size of 56 bit (64 bit with parity). So you cannot use a larger key with it. Mcrypt knows this and silently only uses the first 8 bytes. Mcrypt also doesn't implement proper padding. Instead it pads with 0x00 bytes. You should be able to use a similar, but not same, padding in BouncyCastle:

Cipher.getInstance("DES/ECB/ZeroBytePadding", "BC");

Never use ECB mode. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.

NOTE DES should not be used at all for new developments.

Upvotes: 2

Related Questions