3

I've been chipping away at a school assignment for 3 days, and finally finished it today, error-free and working fine! Except, I was testing it on Java 1.7, and the school servers (where the professor will compile it) run 1.6. So, I tested my code on 1.6, wanting to cover all my bases, and I get a BadPaddingException upon decryption.

[EDIT] Warning: this code does not follow common security practices and should not be used in production code.

Originally, I had this, which works fine on 1.7 (sorry, lots of code.. all relevant..):

public static String aes128(String key, String data, final int direction) {
    SecureRandom rand = new SecureRandom(key.getBytes());
    byte[] randBytes = new byte[16];
    rand.nextBytes(randBytes);
    SecretKey encKey = new SecretKeySpec(randBytes, "AES");

    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("AES");
        cipher.init((direction == ENCRYPT ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), encKey);
    } catch (InvalidKeyException e) {
        return null;
    } catch (NoSuchPaddingException e) {
        return null;
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    try {
        if (direction == ENCRYPT) {
            byte[] encVal = cipher.doFinal(data.getBytes());
            String encryptedValue = Base64.encode(encVal);
            return encryptedValue;
        } else {
            byte[] dataBytes = Base64.decode(data);
            byte[] encVal = cipher.doFinal(dataBytes);
            return new String(encVal);
        }
    } catch (NullPointerException e) {
        return null;
    } catch (BadPaddingException e) {
        return null;
    } catch (IllegalBlockSizeException e) {
        return null;
    }
}

However, my BadPaddingException catch block executes upon decryption:

javax.crypto.BadPaddingException: Given final block not properly padded
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at CipherUtils.aes128(CipherUtils.java:112)
        at CipherUtils.decryptFile(CipherUtils.java:44)
        at decryptFile.main(decryptFile.java:21)

This is what I tried to fix it (basically, I added all the padding/unpadding myself, and used NoPadding):

public static String aes128(String key, String data, final int direction) {
    // PADCHAR = (char)0x10 as String
    while (key.length() % 16 > 0)
        key = key + PADCHAR; // Added this loop

    SecureRandom rand = new SecureRandom(key.getBytes());
    byte[] randBytes = new byte[16];
    rand.nextBytes(randBytes);
    SecretKey encKey = new SecretKeySpec(randBytes, "AES");
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(key.getBytes()); // Created this

    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("AES/CBC/NoPadding"); // Added CBC/NoPadding
        cipher.init((direction == ENCRYPT ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), encKey, paramSpec); // Added paramSpec
    } catch (InvalidKeyException e) {
        return null;
    } catch (NoSuchPaddingException e) {
        return null;
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (InvalidAlgorithmParameterException e) {
        return null; // Added this catch{}
    }

    try {
        if (direction == ENCRYPT) {
            while (data.length() % 16 > 0)
                data = data + PADCHAR; // Added this loop

            byte[] encVal = cipher.doFinal(data.getBytes());
            String encryptedValue = Base64.encode(encVal);
            return encryptedValue;
        } else {
            byte[] dataBytes = Base64.decode(data);
            byte[] encVal = cipher.doFinal(dataBytes);
            return new String(encVal);
        }
    } catch (NullPointerException e) {
        return null;
    } catch (BadPaddingException e) {
        return null;
    } catch (IllegalBlockSizeException e) {
        return null;
    }
}

When using this, I just get gibberish in and out:

Out: u¢;èÉ÷JRLòB±J°N°[9cRÐ{ªv=]I¯¿©:
´RLA©êí;R([¶Ü9¸ßv&%®µ^#û|Bá (80)
Unpadded: u¢;èÉ÷JRLòB±J°N°[9cRÐ{ªv=]I¯¿©:
´RLA©êí;R([¶Ü9¸ßv&%®µ^#û|Bá (79)

It is also worth noting that 1.6 and 1.7 produce different encrypted strings.

For example, on 1.7, encrypting xy (including a SHA-1 hash) with key hi produces:

XLUVZBIJv1n/FV2MzaBK3FLPQRCQF2FY+ghyajdqCGsggAN4aac8bfwscrLaQT7BMHJgfnjJLn+/rwGv0UEW+dbRIMQkNAwkGeSjda3aEpk=

On 1.6, the same thing produces:

nqeahRnA0IuRn7HXUD1JnkhWB5uq/Ng+srUBYE3ycGHDC1QB6Xo7cPU6aEJxH7NKqe3kRN3rT/Ctl/OrhqVkyDDThbkY8LLP39ocC3oP/JE=

I didn't expect the assignment to take so long, so my time has run out and it does need to be done tonight. If there is no answer by then, however, I'll just leave a note to my teacher regarding this. It appears to be some issue that was fixed in 1.7... though hopefully can be remedied through the correct addition/fix in my code.

Thanks a ton for everyone's time!

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Cat
  • 66,919
  • 24
  • 133
  • 141
  • @LanguagesNamedAfterCofee I haven't, unfortunately we're stuck using JCA (Java Cryptographic Architecture), and I wouldn't have time to switch to a new API most likely anyway. – Cat Oct 09 '12 at 00:44
  • 1
    Well, it's worth noting that since your `encKey` is randomized you should expect different results every time you encrypt this. But for me, it's not working with [Java7](http://ideone.com/jOyAQ) or [Java6](http://ideone.com/brAFq) (notes: I made some small modifications to make the code work; and included a haphazardly pasted Base64 method I found online) – NullUserException Oct 09 '12 at 00:57
  • @NullUserException That's just... weird. I'm running it from my 1.7 console now, and it's working fine. `encKey` comes from `SecureRandom`, which is seeded by the key provided. Therefore, if the key is the same, the seed is the same, so the random *should be* the same... – Cat Oct 09 '12 at 01:01
  • 1
    @Eric I'm not convinced this works. I haven't used Java crypto much, but at first glance it looks like you're using a different key every time (thanks to `SecureRandom`), so you can't possibly get the results to be identical. It also means you can't possibly get it to decrypt correctly, even if you get past the padding problem. – NullUserException Oct 09 '12 at 01:08
  • 1
    I deleted my answer because I don't know for sure, but I agree with @NullUserException. – Tim Bender Oct 09 '12 at 01:08
  • @TimBender You were actually right. Well, both of you are right. When I use `new SecretKeySpec(key.getBytes(), "AES")`, it works for encrypting and decrypting. We were told we had to use a PRNG to generate a key, using the given String as a seed. Any idea on how to do this without making it random each time? – Cat Oct 09 '12 at 01:10
  • @Eric You always have to know what key you used to encrypt so it can be used for decryption. If you do randomize the key, you'll have to remember it somehow. – NullUserException Oct 09 '12 at 01:13
  • I usually generate an AES key by taking the user's password and running it through SHA256. Use the first 128 bits generated by the hash algorithm for AES128 and the full 256 bits for AES256. Here's an Objective-C example but it works the same in Java: http://stackoverflow.com/questions/4260108/encrypt-in-objective-c-decrypt-in-ruby-using-anything – par Oct 09 '12 at 01:14
  • Yes, a string is to be entered by the end-user (the "key"), but we're to "*consider the user input as a random seed and use a pseudorandom number generator*" to determine the actual "key". Having said all this, you guys *have* answered the question, so if one or both of you want to post the answer, I'll happily mark it as correct. – Cat Oct 09 '12 at 01:16
  • 2
    The assignment description makes little sense to me. Could you post a link to it maybe? It's fine to stretch the key (like what @par is describing), but it has to be deterministic (ie: it **cannot** be random) so you end up with the same key every time. The random part of the cipher is the [IV](http://en.wikipedia.org/wiki/Initialization_vector), which is used for modes of operation other than ECB. It's used so you don't end up with the same ciphertext when you encrypt the same plaintext. That too, has to be stored along with the encrypted data so it can be used to decrypt it. – NullUserException Oct 09 '12 at 01:16
  • 3
    Oh, BTW, if you need repeatable random digits using a known seed use java.util.Random, not SecureRandom. That will solve your key problem. – par Oct 09 '12 at 01:19
  • (meant: it cannot be random unless it's repeatable random, in which case it's really deterministic). – NullUserException Oct 09 '12 at 01:24
  • Exactly. @NullUserException, feel free to answer this and take the points. Your comment above really is the right analysis. Using Random solves the problem technically but you were first to answer IMO. – par Oct 09 '12 at 01:26
  • I updated and undeleted my answer based on research that I've done. Many examples show generating a raw key using `SecureRandom`, but most explanations say that in practice the value returned by `SecureRandom` is transmitted or stored. Like most things in security, there is absolutely no consensus. – Tim Bender Oct 09 '12 at 01:31
  • 2
    @TimBender Because if you use a block cipher at any mode of operation other than ECB (don't use ECB!), you need an initialization vector. That IV, however it is generated, has to be stored somewhere for decryption. – NullUserException Oct 09 '12 at 01:38
  • @par Random is not meant to be a key derivation function and should not be used that way. – Maarten Bodewes Oct 09 '12 at 17:07
  • 1
    @owlstead I didn't mean to imply that it was, sorry for the confusion, only that Random was what was needed given the constraints of the homework assignment. I think the answers and other comments here make it clear that the assignment falls short of real-world best-practices. – par Oct 10 '12 at 00:21
  • @par I certainly agree with that last comment... – Maarten Bodewes Oct 10 '12 at 09:41

2 Answers2

3

First off:

For almost all systems, encrypting the same plaintext twice should always (i.e. with very very high probability) produce different ciphertext.

The traditional example is that it allows a CPA adversary to distinguish E("attack at dawn") from E("attack at dusk") with only two queries. (There are a handful of systems where you want deterministic encryption, but the right way to do this is "synthetic IV" or cipher modes like CMC and EME.)

Ultimately, the problem is that SecureRandom() is not intended for key derivation.

  • If the input "key" is a passphrase, you should be using something like PBKDF2 (or scrypt() or bcrypt()).
    • Additionally, you should be using an explicit charset, e.g. String.getBytes("UTF-8").
  • If the input "key" is a key, the most common string representation is a hexdump. Java doesn't include an unhexing function, but there are several here.
    • If the input is a "master key" and you want to derive a subkey, then you should be hashing it with other data. There's not much point if the subkey is always the same.

Additional nitpicks:

  • Your code is vulnerable to a padding oracle attack; you really should be verifying a MAC before doing anything with the data (or better, using an authenticated encryption mode).
  • In your second listing, you explicitly reuse the IV. Bad! Assuming CBC mode, the IV used should be unpredictable; SecureRandom is useful here.
Community
  • 1
  • 1
tc.
  • 33,468
  • 5
  • 78
  • 96
  • While I'd love to accept this as the answer, the proposed changes are beyond the scope of my assignment. I've given you an upvote regardless, and would hope others do the same, as this is *very* informative. Thank you! – Cat Oct 09 '12 at 02:09
  • 2
    @Eric: Also, if you're interested in some of the theory behind crypto, I found the [Coursera Cryptography course](https://www.coursera.org/course/crypto) very good and reasonably accessible, but possibly a bit much if you're already a busy student. – tc. Oct 09 '12 at 02:31
  • @tc. Thank you! I'll look into it when I have a lighter course load next semester. – Cat Oct 09 '12 at 05:13
  • 2
    Eric, it's a strange assignment if it's outcome is to create a vulnerable cipher text. – Maarten Bodewes Oct 09 '12 at 17:08
  • @owlstead: I've yet to see a crypto assignment that is CCA-secure - it's simply too easy to get subtly wrong, and I think that teaching people that they're writing "secure" crypto is ultimately a disservice (event MAC verification can have an easy timing sidechannel). It's far more fun (and productive) to teach people how to perform a padding oracle attack. – tc. Oct 12 '12 at 22:12
  • @tc. Yes, that would be a better idea, and its one that is actually employed at the crypto course at coursera. I had already created a framework for it though. – Maarten Bodewes Oct 12 '12 at 22:29
2

I've been looking over and over and I have to agree with NullUserException. The problem is the use of SecureRandom. This means that you never really know what your key is and therefore it is not necessarily ever the same key.

encKey comes from SecureRandom, which is seeded by the key provided. Therefore, if the key is the same, the seed is the same, so the random should be the same...

...unless of course Oracle (or another provider) changes the implementation between versions.

Okay, adding more information that I researched. I think this answer was most helpful.

Get password and cleartext from the user, and convert them to byte arrays.
Generate a secure random salt.
Append the salt to the password and compute its cryptographic hash. Repeat this many times.
Encrypt the cleartext using the resulting hash as the initialization vector and/or secret key.
Save the salt and the resulting ciphertext.

To me, it sounds like SecureRandom is used once to generate a salt but then salt must be saved with the cypher text in order to undo the cyphering process. Additional security comes from repetition and variance of steps (obscurity).

Note: I couldn't find any consensus that these steps are best practices.

Community
  • 1
  • 1
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • See http://stackoverflow.com/questions/8259272/why-is-securerandom-in-java-called-cs-prng-and-not-trng -- SecureRandom would use /dev/urandom on Linux and be truly random. – par Oct 09 '12 at 01:29
  • 4
    re: best practices, the question is apparently a homework assignment and the key generation method using a PRNG is *NOT* a good solution to the problem. You need a deterministic way to get a predetermined number of bits and users are apt to give low-entropy passwords like "love" or "god" or somesuch. A strong passphrase can give too many bits. Generally this is why running whatever the user input is through SHA256 is a good way to get repeatable key bits. Then you don't rely on a PRNG implementation that can change, and you get a key that works every time. – par Oct 09 '12 at 01:39
  • And I will say using a salt is a good idea, but it has to be passed along outside of the encrypted bits, either stored somewhere or generated by the algorithm using a repeatable PRNG, but there again you have the problem of making sure the PRNG implementation can't change out from under you, which it can with SecureRandom. – par Oct 09 '12 at 01:45
  • Alright, I've got it all working using NullUserException's information as well as par's `Random` idea, and most of that is contained within this answer, so I've accepted it. Thanks to all 3 of you! – Cat Oct 09 '12 at 02:09