 apps/enc.c       | 143 +++++++++++++++++++++++++++++++++++++++----------------
 doc/apps/enc.pod |  16 +++++--
 2 files changed, 116 insertions(+), 43 deletions(-)

diff --git a/apps/enc.c b/apps/enc.c
index 520ee47..cb41a9e 100644
--- a/apps/enc.c
+++ b/apps/enc.c
@@ -77,7 +77,7 @@
 #define SIZE    (512)
 #define BSIZE   (8*1024)
 
-static int set_hex(char *in, unsigned char *out, int size);
+static int set_hex(const char *in, unsigned char *out, int size);
 static void show_ciphers(const OBJ_NAME *name, void *bio_);
 
 typedef enum OPTION_choice {
@@ -85,7 +85,7 @@ typedef enum OPTION_choice {
     OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V,
     OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A,
     OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE,
-    OPT_UPPER_S, OPT_IV, OPT_MD, OPT_CIPHER
+    OPT_UPPER_S, OPT_IV, OPT_MD, OPT_ITER, OPT_V2, OPT_CIPHER
 } OPTION_CHOICE;
 
 OPTIONS enc_options[] = {
@@ -113,6 +113,8 @@ OPTIONS enc_options[] = {
     {"S", OPT_UPPER_S, 's', "Salt, in hex"},
     {"iv", OPT_IV, 's', "IV in hex"},
     {"md", OPT_MD, 's', "Use specified digest to create key from passphrase"},
+    {"iter", OPT_ITER, 'p', "Specify the iteration count"},
+    {"v2", OPT_V2, '-', "Use PKCS#5 v2.0"},
     {"none", OPT_NONE, '-', "Don't encrypt"},
     {"", OPT_CIPHER, '-', "Any supported cipher"},
 #ifdef ZLIB
@@ -143,8 +145,13 @@ int enc_main(int argc, char **argv)
     int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY;
     int ret = 1, inl, nopad = 0;
     unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
-    unsigned char *buff = NULL, salt[PKCS5_SALT_LEN];
+    unsigned char *buff = NULL, salt[PKCS5_SALT_LEN], fsalt[PKCS5_SALT_LEN];
+    int iter = 1; /* backward compatibility */
+    int v2 = 0;
     long n;
+    int streamable = 1; /* don't forget some modes aren't */
+    int wrap = 0;
+
 #ifdef ZLIB
     int do_zlib = 0;
     BIO *bzl = NULL;
@@ -286,6 +293,12 @@ int enc_main(int argc, char **argv)
                 goto opthelp;
             cipher = c;
             break;
+        case OPT_ITER:
+            iter = atoi(opt_arg());
+            break;
+        case OPT_V2:
+            v2 = 1;
+            break;
         case OPT_NONE:
             cipher = NULL;
             break;
@@ -304,6 +317,11 @@ int enc_main(int argc, char **argv)
         goto end;
     }
 
+    if (EVP_CIPHER_mode(cipher) == EVP_CIPH_WRAP_MODE) {
+        wrap = 1;
+        streamable = 0;
+    }
+
     if (dgst == NULL)
         dgst = EVP_sha256();
 
@@ -331,6 +349,10 @@ int enc_main(int argc, char **argv)
     }
 
     if (infile == NULL) {
+        if (!streamable) {
+            BIO_printf(bio_err, "Unstreamable cipher mode\n");
+            goto end;
+        }
         unbuffer(stdin);
         in = dup_bio_in(informat);
     } else
@@ -404,27 +426,26 @@ int enc_main(int argc, char **argv)
     }
 
     if (cipher != NULL) {
-        /*
-         * Note that str is NULL if a key was passed on the command line, so
-         * we get no salt in that case. Is this a bug?
-         */
-        if (str != NULL) {
+
+        if (str != NULL) { /* a passphrase is available */
             /*
-             * Salt handling: if encrypting generate a salt and write to
-             * output BIO. If decrypting read salt from input BIO.
+             * Salt handling: if encrypting generate a salt if not supplied,
+             * and write to output BIO. If decrypting use salt from input BIO
+             * if not given with args
              */
             unsigned char *sptr;
             if (nosalt)
                 sptr = NULL;
             else {
-                if (enc) {
-                    if (hsalt) {
-                        if (!set_hex(hsalt, salt, sizeof salt)) {
-                            BIO_printf(bio_err, "invalid hex salt value\n");
-                            goto end;
-                        }
-                    } else if (RAND_bytes(salt, sizeof salt) <= 0)
+                if (hsalt != NULL && !set_hex(hsalt, salt, sizeof salt)) {
+                    BIO_printf(bio_err, "invalid hex salt value\n");
+                    goto end;
+                }
+                if (enc) {  /* encryption */
+                    if (hsalt == NULL && RAND_bytes(salt, sizeof salt) <= 0) {
+                        BIO_printf(bio_err, "RAND_bytes failed\n");
                         goto end;
+                    }
                     /*
                      * If -P option then don't bother writing
                      */
@@ -437,26 +458,57 @@ int enc_main(int argc, char **argv)
                         BIO_printf(bio_err, "error writing output file\n");
                         goto end;
                     }
-                } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
-                           || BIO_read(rbio,
-                                       (unsigned char *)salt,
-                                       sizeof salt) != sizeof salt) {
-                    BIO_printf(bio_err, "error reading input file\n");
-                    goto end;
-                } else if (memcmp(mbuf, magic, sizeof magic - 1)) {
-                    BIO_printf(bio_err, "bad magic number\n");
-                    goto end;
-                }
+                } else {    /* decryption */
+                    int fsalted = 0;
 
+                    if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf) {
+                        BIO_printf(bio_err, "error reading input file\n");
+                        goto end;
+                    }
+                    if (memcmp(mbuf, magic, sizeof mbuf) == 0) { /* file IS salted */
+                        if (BIO_read(rbio, fsalt,
+                                     sizeof fsalt) != sizeof fsalt) {
+                            BIO_printf(bio_err, "error reading input file\n");
+                            goto end;
+                        }
+                        else fsalted = 1;
+                    }
+                    else { /* file is NOT salted */
+                        if ( hsalt == NULL ) { /* NO salt at all */
+                            BIO_printf(bio_err, "bad magic number\n");
+                            goto end;
+                        }
+                        else { /* need to rewind */
+                            if (BIO_reset(rbio)) {
+                                BIO_printf(bio_err, "BIO_reset failed\n");
+                                goto end;
+                            };
+                        }
+                    }
+                    if(fsalted && hsalt == NULL)
+                        memcpy(salt, fsalt, sizeof salt);
+                }
                 sptr = salt;
             }
 
-            if (!EVP_BytesToKey(cipher, dgst, sptr,
-                                (unsigned char *)str,
-                                strlen(str), 1, key, iv)) {
-                BIO_printf(bio_err, "EVP_BytesToKey failed\n");
-                goto end;
+            if (v2 == 1) {
+                if (!PKCS5_PBKDF2_HMAC(str, -1, sptr, sizeof(salt), iter,
+                                       dgst,
+                                       EVP_CIPHER_key_length(cipher), key)) {
+                    BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n");
+                    goto end;
+                }
+                memset( iv, 0, sizeof(iv) ); /* in case no hiv args */
             }
+            else {
+                if (!EVP_BytesToKey(cipher, dgst, sptr,
+                                    (unsigned char *)str,
+                                    strlen(str), iter, key, iv)) {
+                    BIO_printf(bio_err, "EVP_BytesToKey failed\n");
+                    goto end;
+                }
+            }
+
             /*
              * zero the complete buffer or the string passed from the command
              * line bug picked up by Larry J. Hughes Jr. <hughes@indiana.edu>
@@ -466,17 +518,19 @@ int enc_main(int argc, char **argv)
             else
                 OPENSSL_cleanse(str, strlen(str));
         }
+
         if (hiv != NULL) {
             int siz = EVP_CIPHER_iv_length(cipher);
             if (siz == 0) {
                 BIO_printf(bio_err, "warning: iv not use by this cipher\n");
-            } else if (!set_hex(hiv, iv, sizeof iv)) {
+            } else if (!set_hex(hiv, iv, siz)) {
                 BIO_printf(bio_err, "invalid hex iv value\n");
                 goto end;
             }
         }
         if ((hiv == NULL) && (str == NULL)
-            && EVP_CIPHER_iv_length(cipher) != 0) {
+            && EVP_CIPHER_iv_length(cipher) != 0
+            && wrap == 0) {
             /*
              * No IV was explicitly set and no IV was generated during
              * EVP_BytesToKey. Hence the IV is undefined, making correct
@@ -500,6 +554,9 @@ int enc_main(int argc, char **argv)
 
         BIO_get_cipher_ctx(benc, &ctx);
 
+        if (wrap == 1)
+            EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
+
         if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) {
             BIO_printf(bio_err, "Error setting cipher %s\n",
                        EVP_CIPHER_name(cipher));
@@ -510,7 +567,8 @@ int enc_main(int argc, char **argv)
         if (nopad)
             EVP_CIPHER_CTX_set_padding(ctx, 0);
 
-        if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) {
+        if (!EVP_CipherInit_ex(ctx, NULL, NULL, key,
+                               (hiv == NULL && wrap == 1 ? NULL : iv), enc)) {
             BIO_printf(bio_err, "Error setting cipher %s\n",
                        EVP_CIPHER_name(cipher));
             ERR_print_errors(bio_err);
@@ -556,10 +614,16 @@ int enc_main(int argc, char **argv)
         inl = BIO_read(rbio, (char *)buff, bsize);
         if (inl <= 0)
             break;
+        if (!streamable && !BIO_eof(rbio)) {    /* do not output data */
+            BIO_printf(bio_err, "Unstreamable cipher mode\n");
+            goto end;
+        }
         if (BIO_write(wbio, (char *)buff, inl) != inl) {
             BIO_printf(bio_err, "error writing output file\n");
             goto end;
         }
+        if (!streamable)
+            break;
     }
     if (!BIO_flush(wbio)) {
         BIO_printf(bio_err, "bad decrypt\n");
@@ -602,20 +666,19 @@ static void show_ciphers(const OBJ_NAME *name, void *bio_)
         BIO_printf(bio, " ");
 }
 
-static int set_hex(char *in, unsigned char *out, int size)
+static int set_hex(const char *in, unsigned char *out, int size)
 {
     int i, n;
     unsigned char j;
 
     n = strlen(in);
-    if (n > (size * 2)) {
-        BIO_printf(bio_err, "hex string is too long\n");
+    if (n < (size * 2)) { /* ignore if longer */
+        BIO_printf(bio_err, "hex string is too short\n");
         return (0);
     }
     memset(out, 0, size);
     for (i = 0; i < n; i++) {
-        j = (unsigned char)*in;
-        *(in++) = '\0';
+        j = (unsigned char)*in++;
         if (j == 0)
             break;
         if (!isxdigit(j)) {
diff --git a/doc/apps/enc.pod b/doc/apps/enc.pod
index 62e1383..4447cd1 100644
--- a/doc/apps/enc.pod
+++ b/doc/apps/enc.pod
@@ -24,6 +24,8 @@ B<openssl enc -ciphername>
 [B<-nosalt>]
 [B<-z>]
 [B<-md digest>]
+[B<-iter count>]
+[B<-v2>]
 [B<-p>]
 [B<-P>]
 [B<-bufsize number>]
@@ -98,6 +100,15 @@ the B<-pass> argument.
 Use the specified digest to create the key from the passphrase.
 The default algorithm is sha-256.
 
+=item B<-iter count>
+
+Use a given number of iterations on the password in deriving the encryption key.
+High values increase the time required to brute-force the resulting file.
+
+=item B<-v2>
+
+This option enables the use of PKCS#5 v2.0 algorithms to derive the key.
+
 =item B<-nosalt>
 
 don't use a salt in the key derivation routines. This option B<SHOULD NOT> be
@@ -140,7 +151,8 @@ or decryption.
 
 =item B<-bufsize number>
 
-set the buffer size for I/O
+set the buffer size for I/O. Default is 8K. For some unstreamable cipher modes,
+try setting a value greater than the file size. 
 
 =item B<-nopad>
 
@@ -326,8 +338,6 @@ Decrypt some data using a supplied 40 bit RC4 key:
 
 The B<-A> option when used with large files doesn't work properly.
 
-There should be an option to allow an iteration count to be included.
-
 The B<enc> program only supports a fixed number of algorithms with
 certain parameters. So if, for example, you want to use RC2 with a
 76 bit key or RC4 with an 84 bit key you can't use this program.
